Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support url form encoded marshaler and response in JSON #3711

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
56 changes: 56 additions & 0 deletions runtime/marshal_urlencode.go
@@ -0,0 +1,56 @@
package runtime

import (
"fmt"
"io"
"io/ioutil"
"net/url"

"github.com/grpc-ecosystem/grpc-gateway/v2/utilities"
"google.golang.org/protobuf/proto"
)

type UrlEncodeMarshal struct {
Marshaler
}

// ContentType means the content type of the response
func (u UrlEncodeMarshal) ContentType(_ interface{}) string {
return "application/json"
}

func (u UrlEncodeMarshal) Marshal(v interface{}) ([]byte, error) {
// can marshal the response in proto message format
j := JSONPb{}
return j.Marshal(v)
}

// NewDecoder indicates how to decode the request
func (u UrlEncodeMarshal) NewDecoder(r io.Reader) Decoder {
return DecoderFunc(func(p interface{}) error {
msg, ok := p.(proto.Message)
if !ok {
return fmt.Errorf("not proto message")
}

formData, err := ioutil.ReadAll(r)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use io.ReadAll

if err != nil {
return err
}

values, err := url.ParseQuery(string(formData))
if err != nil {
return err
}

filter := &utilities.DoubleArray{}

err = PopulateQueryParameters(msg, values, filter)

if err != nil {
return err
}

return nil
Comment on lines +48 to +54
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since we're not mutating the error before returning, we can just

Suggested change
err = PopulateQueryParameters(msg, values, filter)
if err != nil {
return err
}
return nil
return PopulateQueryParameters(msg, values, filter)

})
}