fix nil nmsg in case of empty request body

This commit is contained in:
Nurzhan Ilyassov 2024-03-26 11:09:38 +05:00 committed by Vasiliy Tolstov
parent 9149aeb3de
commit 4c2178305d
2 changed files with 33 additions and 1 deletions

10
util.go
View File

@ -217,13 +217,21 @@ func newPathRequest(path string, method string, body string, msg interface{}, ta
_, _ = b.WriteString(values.Encode()) _, _ = b.WriteString(values.Encode())
} }
if rutil.IsZero(nmsg) { if rutil.IsZero(nmsg) && !isEmptyStruct(nmsg) {
return b.String(), nil, nil return b.String(), nil, nil
} }
return b.String(), nmsg, nil return b.String(), nmsg, nil
} }
func isEmptyStruct(v interface{}) bool {
val := reflect.ValueOf(v)
if val.Kind() == reflect.Ptr {
val = val.Elem()
}
return val.Kind() == reflect.Struct && val.NumField() == 0
}
func newTemplate(path string) ([]string, error) { func newTemplate(path string) ([]string, error) {
if len(path) == 0 || path[0] != '/' { if len(path) == 0 || path[0] != '/' {
return nil, fmt.Errorf("path must starts with /") return nil, fmt.Errorf("path must starts with /")

View File

@ -59,6 +59,30 @@ func TestNewPathRequest(t *testing.T) {
} }
} }
func TestNewPathRequestWithEmptyBody(t *testing.T) {
val := struct{}{}
for _, m := range []string{"POST", "PUT", "PATCH", "GET", "DELETE"} {
body := `{"type": "invalid"}`
path, nmsg, err := newPathRequest("/v1/test", m, body, val, []string{"protobuf", "json"}, nil)
if err != nil {
t.Fatal(err)
}
if nmsg == nil {
t.Fatalf("invalid path: nil nmsg")
}
u, err := url.Parse(path)
if err != nil {
t.Fatal(err)
}
vals := u.Query()
if len(vals) != 0 {
t.Fatalf("invalid path: %v nmsg: %v", path, nmsg)
}
}
}
func TestNewPathVarRequest(t *testing.T) { func TestNewPathVarRequest(t *testing.T) {
type Message struct { type Message struct {
Name string `json:"name"` Name string `json:"name"`