Skip to content

Commit

Permalink
httpclient
Browse files Browse the repository at this point in the history
  • Loading branch information
lvphps committed Aug 9, 2023
1 parent ce5e78d commit b6cff05
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
16 changes: 16 additions & 0 deletions rest/httpc/requests.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,15 @@ func buildRequest(ctx context.Context, method, url string, data any) (*http.Requ
reader = &buf
}

formVars, hasFormBody := val[formKey]
if hasFormBody && method == http.MethodPost {
DataUrlVal := nurl.Values{}
for key, val := range formVars {
DataUrlVal.Add(key, val.(string))
}
reader = strings.NewReader(DataUrlVal.Encode())
}

req, err := http.NewRequestWithContext(ctx, method, u.String(), reader)
if err != nil {
return nil, err
Expand All @@ -107,12 +116,19 @@ func buildRequest(ctx context.Context, method, url string, data any) (*http.Requ
if hasJsonBody {
req.Header.Set(header.ContentType, header.JsonContentType)
}
if hasFormBody && method == http.MethodPost {
req.Header.Set(header.ContentType, header.XwwwFromUrlencoded)
}

return req, nil
}

func fillHeader(r *http.Request, val map[string]any) {
for k, v := range val {
//note 自定义host需要单独处理
if strings.ToLower(k) == "host" {
r.Host = fmt.Sprint(v)
}
r.Header.Add(k, fmt.Sprint(v))
}
}
Expand Down
2 changes: 2 additions & 0 deletions rest/internal/header/headers.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,6 @@ const (
ContentType = "Content-Type"
// JsonContentType is the content type for JSON.
JsonContentType = "application/json; charset=utf-8"
// XwwwFromUrlencoded is the content type for application/x-www-form-urlencoded.
XwwwFromUrlencoded = "application/x-www-form-urlencoded"
)

0 comments on commit b6cff05

Please sign in to comment.