Skip to content

Commit

Permalink
FormatRequestBody
Browse files Browse the repository at this point in the history
  • Loading branch information
chyroc committed May 6, 2024
1 parent 2bf225e commit b29fb96
Showing 1 changed file with 70 additions and 0 deletions.
70 changes: 70 additions & 0 deletions impl_request.go
Original file line number Diff line number Diff line change
Expand Up @@ -509,3 +509,73 @@ func (r *defaultHttpClient) Do(ctx context.Context, req *http.Request) (*http.Re
req = req.WithContext(ctx)
return r.ins.Do(req)
}

func FormatRequestBody(body interface{}) map[string]interface{} {
queries := url.Values{}
headers := url.Values{}
res := map[string]interface{}{}
keys := map[string]bool{}

if err := rangeStruct(body, func(fieldVV reflect.Value, fieldVT reflect.StructField) error {
if path := fieldVT.Tag.Get("path"); path != "" {
for keys[path] {
path = path + ".path"
}
keys[path] = true
res[path] = internal.ReflectToString(fieldVV)
} else if queryKey := fieldVT.Tag.Get("query"); queryKey != "" {
value := internal.ReflectToQueryString(fieldVV)
sep := fieldVT.Tag.Get("join_sep")
if sep != "" {
queries.Add(queryKey, strings.Join(value, sep))
} else {
for _, v := range value {
queries.Add(queryKey, v)
}
}
} else if header := fieldVT.Tag.Get("header"); header != "" {
switch header {
case "range":
if fieldVV.Kind() != reflect.Array || fieldVV.Len() != 2 || fieldVV.Index(0).Kind() != reflect.Int64 {
return fmt.Errorf("with range header, value must be [2]int64")
}
from := fieldVV.Index(0).Int()
to := fieldVV.Index(1).Int()
if from != 0 || to != 0 {
headers.Add("range", fmt.Sprintf("bytes=%d-%d", from, to))
}
}
} else if j := fieldVT.Tag.Get("json"); j != "" {
if strings.HasSuffix(j, ",omitempty") {
j = j[:len(j)-10]
}
for keys[j] {
j = j + ".json"
}
keys[j] = true
if _, ok := fieldVV.Interface().(io.Reader); ok {
res[j] = "<FILE>"
} else {
res[j] = internal.ReflectToString(fieldVV)
}
}
return nil
}); err != nil {
return res
}
for k, v := range headers {
for keys[k] {
k = k + ".header"
}
keys[k] = true
res[k] = v
}
for k, v := range queries {
for keys[k] {
k = k + ".query"
}
keys[k] = true
res[k] = v
}
return res
}

0 comments on commit b29fb96

Please sign in to comment.