token_url.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package token
  2. import (
  3. "crypto/md5"
  4. "encoding/base64"
  5. "encoding/hex"
  6. "errors"
  7. "fmt"
  8. "net/url"
  9. "strings"
  10. )
  11. // UrlSign
  12. // path 请求的路径 (不附带 querystring)
  13. func (t *token) UrlSign(path string, method string, params url.Values) (tokenString string, err error) {
  14. // 合法的 Methods
  15. methods := map[string]bool{
  16. "get": true,
  17. "post": true,
  18. "put": true,
  19. "path": true,
  20. "delete": true,
  21. "head": true,
  22. "options": true,
  23. }
  24. methodName := strings.ToLower(method)
  25. if !methods[methodName] {
  26. err = errors.New("method param error")
  27. return
  28. }
  29. // Encode() 方法中自带 sorted by key
  30. sortParamsEncode := params.Encode()
  31. // 加密字符串规则 path + method + sortParamsEncode + secret
  32. encryptStr := fmt.Sprintf("%s%s%s%s", path, methodName, sortParamsEncode, t.secret)
  33. // 对加密字符串进行 md5
  34. s := md5.New()
  35. s.Write([]byte(encryptStr))
  36. md5Str := hex.EncodeToString(s.Sum(nil))
  37. // 对 md5Str 进行 base64 encode
  38. tokenString = base64.StdEncoding.EncodeToString([]byte(md5Str))
  39. return
  40. }