You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
54 lines
1.2 KiB
Go
54 lines
1.2 KiB
Go
2 years ago
|
package internal
|
||
2 years ago
|
|
||
|
import (
|
||
|
"bytes"
|
||
|
"encoding/json"
|
||
|
"net/http"
|
||
|
|
||
|
"github.com/fullstorydev/grpcurl"
|
||
|
"github.com/golang/protobuf/jsonpb"
|
||
2 years ago
|
"github.com/zeromicro/go-zero/rest/httpx"
|
||
2 years ago
|
"github.com/zeromicro/go-zero/rest/pathvar"
|
||
|
)
|
||
|
|
||
2 years ago
|
// NewRequestParser creates a new request parser from the given http.Request and resolver.
|
||
|
func NewRequestParser(r *http.Request, resolver jsonpb.AnyResolver) (grpcurl.RequestParser, error) {
|
||
2 years ago
|
vars := pathvar.Vars(r)
|
||
2 years ago
|
params, err := httpx.GetFormValues(r)
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
for k, v := range vars {
|
||
|
params[k] = v
|
||
|
}
|
||
|
if len(params) == 0 {
|
||
2 years ago
|
return grpcurl.NewJSONRequestParser(r.Body, resolver), nil
|
||
|
}
|
||
|
|
||
|
if r.ContentLength == 0 {
|
||
2 years ago
|
return buildJsonRequestParser(params, resolver)
|
||
2 years ago
|
}
|
||
|
|
||
|
m := make(map[string]interface{})
|
||
|
if err := json.NewDecoder(r.Body).Decode(&m); err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
2 years ago
|
for k, v := range params {
|
||
2 years ago
|
m[k] = v
|
||
|
}
|
||
|
|
||
2 years ago
|
return buildJsonRequestParser(m, resolver)
|
||
2 years ago
|
}
|
||
2 years ago
|
|
||
|
func buildJsonRequestParser(m map[string]interface{}, resolver jsonpb.AnyResolver) (
|
||
|
grpcurl.RequestParser, error) {
|
||
|
var buf bytes.Buffer
|
||
|
if err := json.NewEncoder(&buf).Encode(m); err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
return grpcurl.NewJSONRequestParser(&buf, resolver), nil
|
||
|
}
|