2022-07-17 12:37:23 +08:00
|
|
|
package internal
|
2022-07-16 14:11:34 +08:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"encoding/json"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/fullstorydev/grpcurl"
|
|
|
|
"github.com/golang/protobuf/jsonpb"
|
2022-07-16 23:40:53 +08:00
|
|
|
"github.com/zeromicro/go-zero/rest/httpx"
|
2022-07-16 14:11:34 +08:00
|
|
|
"github.com/zeromicro/go-zero/rest/pathvar"
|
|
|
|
)
|
|
|
|
|
2022-07-17 12:37:23 +08:00
|
|
|
// NewRequestParser creates a new request parser from the given http.Request and resolver.
|
|
|
|
func NewRequestParser(r *http.Request, resolver jsonpb.AnyResolver) (grpcurl.RequestParser, error) {
|
2022-07-16 14:11:34 +08:00
|
|
|
vars := pathvar.Vars(r)
|
2022-07-16 23:40:53 +08:00
|
|
|
params, err := httpx.GetFormValues(r)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
for k, v := range vars {
|
|
|
|
params[k] = v
|
|
|
|
}
|
|
|
|
if len(params) == 0 {
|
2022-07-16 14:11:34 +08:00
|
|
|
return grpcurl.NewJSONRequestParser(r.Body, resolver), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if r.ContentLength == 0 {
|
2022-07-16 23:40:53 +08:00
|
|
|
return buildJsonRequestParser(params, resolver)
|
2022-07-16 14:11:34 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
m := make(map[string]interface{})
|
|
|
|
if err := json.NewDecoder(r.Body).Decode(&m); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2022-07-16 23:40:53 +08:00
|
|
|
for k, v := range params {
|
2022-07-16 14:11:34 +08:00
|
|
|
m[k] = v
|
|
|
|
}
|
|
|
|
|
2022-07-16 22:59:25 +08:00
|
|
|
return buildJsonRequestParser(m, resolver)
|
2022-07-16 14:11:34 +08:00
|
|
|
}
|
2022-07-17 12:37:23 +08:00
|
|
|
|
|
|
|
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
|
|
|
|
}
|