Skip to content

Commit

Permalink
rest: support read request body
Browse files Browse the repository at this point in the history
  • Loading branch information
chai2010 committed Jul 17, 2018
1 parent 75cbd00 commit 86aa268
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 33 deletions.
67 changes: 38 additions & 29 deletions pbgo.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions pbgo.proto
Expand Up @@ -28,8 +28,8 @@ message CustomHttpRule {
string method = 1;
string url = 2;

string content_type = 3; // must be 'string' type
string content_body = 4; // must be 'bytes' type

string content_type = 3; // must be 'string' type
string content_body = 4; // must be 'bytes' type
string custom_header = 5; // must be 'map<string,string>' type
string request_body = 6; // must be 'bytes' type
}
17 changes: 16 additions & 1 deletion protoc-gen-pbgo/pbgo.go
Expand Up @@ -65,10 +65,12 @@ type ServiceRestMethodSpec struct {
ContentType string
ContentBody string
CustomHeader string
RequestBody string
}

func (p *pbgoPlugin) genImportCode(file *generator.FileDescriptor) {
p.P(`import "encoding/json"`)
p.P(`import "io/ioutil"`)
p.P(`import "net/rpc"`)
p.P(`import "net/http"`)
p.P(`import "regexp"`)
Expand All @@ -82,6 +84,7 @@ func (p *pbgoPlugin) genReferenceImportCode(file *generator.FileDescriptor) {
p.P("// Reference imports to suppress errors if they are not otherwise used.")
p.P("var _ = json.Marshal")
p.P("var _ = http.ListenAndServe")
p.P("var _ = ioutil.ReadAll")
p.P("var _ = regexp.Match")
p.P("var _ = strings.Split")
p.P("var _ = pbgo.PopulateFieldFromPath")
Expand Down Expand Up @@ -135,6 +138,7 @@ func (p *pbgoPlugin) buildRestMethodSpec(m *descriptor.MethodDescriptorProto) []
ContentType: v.ContentType,
ContentBody: v.ContentBody,
CustomHeader: v.CustomHeader,
RequestBody: v.RequestBody,
})
}
}
Expand Down Expand Up @@ -265,7 +269,18 @@ func {{.ServiceName}}Handler(svc {{.ServiceName}}Interface) http.Handler {
return
}
{{if or (eq "POST" $rest.Method) (eq "PUT" $rest.Method) (eq "PATCH" $rest.Method)}}
{{if $rest.RequestBody}}
rBody, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
err := pbgo.PopulateFieldFromPath(&protoReq, "{{$rest.RequestBody}}", rBody)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
{{else if or (eq "POST" $rest.Method) (eq "PUT" $rest.Method) (eq "PATCH" $rest.Method)}}
if err := json.NewDecoder(r.Body).Decode(&protoReq); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
Expand Down

0 comments on commit 86aa268

Please sign in to comment.