Skip to content

Commit

Permalink
支持在请求前修改各api的地址 (#736)
Browse files Browse the repository at this point in the history
* 增加URI修改接口,以支持正向代理

* Update http.go

* Update http.go
  • Loading branch information
zxfishhack committed Nov 2, 2023
1 parent 0ffe341 commit a5e674b
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions util/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,26 @@ import (
"golang.org/x/crypto/pkcs12"
)

// URIModifier URI修改器
type URIModifier func(uri string) string

var uriModifier URIModifier

// SetURIModifier 设置URI修改器
func SetURIModifier(fn URIModifier) {
uriModifier = fn
}

// HTTPGet get 请求
func HTTPGet(uri string) ([]byte, error) {
return HTTPGetContext(context.Background(), uri)
}

// HTTPGetContext get 请求
func HTTPGetContext(ctx context.Context, uri string) ([]byte, error) {
if uriModifier != nil {
uri = uriModifier(uri)
}
request, err := http.NewRequestWithContext(ctx, http.MethodGet, uri, nil)
if err != nil {
return nil, err
Expand All @@ -47,6 +60,9 @@ func HTTPPost(uri string, data string) ([]byte, error) {

// HTTPPostContext post 请求
func HTTPPostContext(ctx context.Context, uri string, data []byte, header map[string]string) ([]byte, error) {
if uriModifier != nil {
uri = uriModifier(uri)
}
body := bytes.NewBuffer(data)
request, err := http.NewRequestWithContext(ctx, http.MethodPost, uri, body)
if err != nil {
Expand All @@ -71,6 +87,9 @@ func HTTPPostContext(ctx context.Context, uri string, data []byte, header map[st

// PostJSONContext post json 数据请求
func PostJSONContext(ctx context.Context, uri string, obj interface{}) ([]byte, error) {
if uriModifier != nil {
uri = uriModifier(uri)
}
jsonBuf := new(bytes.Buffer)
enc := json.NewEncoder(jsonBuf)
enc.SetEscapeHTML(false)
Expand Down Expand Up @@ -146,6 +165,9 @@ type MultipartFormField struct {

// PostMultipartForm 上传文件或其他多个字段
func PostMultipartForm(fields []MultipartFormField, uri string) (respBody []byte, err error) {
if uriModifier != nil {
uri = uriModifier(uri)
}
bodyBuf := &bytes.Buffer{}
bodyWriter := multipart.NewWriter(bodyBuf)

Expand Down Expand Up @@ -198,6 +220,9 @@ func PostMultipartForm(fields []MultipartFormField, uri string) (respBody []byte

// PostXML perform a HTTP/POST request with XML body
func PostXML(uri string, obj interface{}) ([]byte, error) {
if uriModifier != nil {
uri = uriModifier(uri)
}
xmlData, err := xml.Marshal(obj)
if err != nil {
return nil, err
Expand Down Expand Up @@ -259,6 +284,9 @@ func pkcs12ToPem(p12 []byte, password string) tls.Certificate {

// PostXMLWithTLS perform a HTTP/POST request with XML body and TLS
func PostXMLWithTLS(uri string, obj interface{}, ca, key string) ([]byte, error) {
if uriModifier != nil {
uri = uriModifier(uri)
}
xmlData, err := xml.Marshal(obj)
if err != nil {
return nil, err
Expand Down

0 comments on commit a5e674b

Please sign in to comment.