github.com/gogf/gf@v1.16.9/.example/net/ghttp/client/middleware/client.go (about)

     1  package main
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"github.com/gogf/gf/container/garray"
     7  	"github.com/gogf/gf/crypto/gmd5"
     8  	"github.com/gogf/gf/frame/g"
     9  	"github.com/gogf/gf/internal/json"
    10  	"github.com/gogf/gf/net/ghttp"
    11  	"github.com/gogf/gf/os/gtime"
    12  	"github.com/gogf/gf/util/gconv"
    13  	"github.com/gogf/gf/util/guid"
    14  	"github.com/gogf/gf/util/gutil"
    15  	"io/ioutil"
    16  	"net/http"
    17  )
    18  
    19  const (
    20  	appId     = "123"
    21  	appSecret = "456"
    22  )
    23  
    24  // 注入统一的接口签名参数
    25  func injectSignature(jsonContent []byte) []byte {
    26  	var m map[string]interface{}
    27  	_ = json.Unmarshal(jsonContent, &m)
    28  	if len(m) > 0 {
    29  		m["appid"] = appId
    30  		m["nonce"] = guid.S()
    31  		m["timestamp"] = gtime.Timestamp()
    32  		var (
    33  			keyArray   = garray.NewSortedStrArrayFrom(gutil.Keys(m))
    34  			sigContent string
    35  		)
    36  		keyArray.Iterator(func(k int, v string) bool {
    37  			sigContent += v
    38  			sigContent += gconv.String(m[v])
    39  			return true
    40  		})
    41  		m["signature"] = gmd5.MustEncryptString(gmd5.MustEncryptString(sigContent) + appSecret)
    42  		jsonContent, _ = json.Marshal(m)
    43  	}
    44  	return jsonContent
    45  }
    46  
    47  func main() {
    48  	c := g.Client()
    49  	c.Use(func(c *ghttp.Client, r *http.Request) (resp *ghttp.ClientResponse, err error) {
    50  		bodyBytes, _ := ioutil.ReadAll(r.Body)
    51  		if len(bodyBytes) > 0 {
    52  			// 注入签名相关参数,修改Request原有的提交参数
    53  			bodyBytes = injectSignature(bodyBytes)
    54  			r.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
    55  			r.ContentLength = int64(len(bodyBytes))
    56  		}
    57  		return c.Next(r)
    58  	})
    59  	content := c.ContentJson().PostContent("http://127.0.0.1:8199/", g.Map{
    60  		"name": "goframe",
    61  		"site": "https://goframe.org",
    62  	})
    63  	fmt.Println(content)
    64  }