sign.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. // Copyright 2013 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package shell implements calculate signature for shell(pay system) query parameters.
  5. //
  6. // As a simple example:
  7. //
  8. // type Options struct {
  9. // Query string `json:"q"`
  10. // ShowAll bool `json:"all"`
  11. // Page int `json:"page,omitempty"`
  12. // }
  13. // use json tags
  14. //
  15. package shell
  16. import (
  17. "bytes"
  18. "crypto/md5"
  19. "fmt"
  20. "io"
  21. "net/url"
  22. "reflect"
  23. "sort"
  24. "strconv"
  25. "strings"
  26. "time"
  27. )
  28. var timeType = reflect.TypeOf(time.Time{})
  29. //var encoderType = reflect.TypeOf(new(Encoder)).Elem()
  30. // Encoder is an interface implemented by any type that wishes to encode
  31. // itself into URL values in a non-standard way.
  32. type Encoder interface {
  33. EncodeValues(key string, v *url.Values) error
  34. }
  35. //Sign sign for shell request
  36. func Sign(v interface{}, token string) (sign string, err error) {
  37. var param string
  38. param, err = Encode(v)
  39. if err != nil {
  40. return
  41. }
  42. var final = param + "&token=" + token
  43. var h = md5.New()
  44. io.WriteString(h, final)
  45. var result = h.Sum(nil)
  46. sign = fmt.Sprintf("%x", result)
  47. return
  48. }
  49. // Encode encode with dictinary ascending order
  50. func Encode(v interface{}) (res string, err error) {
  51. val := reflect.ValueOf(v)
  52. for val.Kind() == reflect.Ptr {
  53. if val.IsNil() {
  54. return "", nil
  55. }
  56. val = val.Elem()
  57. }
  58. if v == nil {
  59. return "", nil
  60. }
  61. if val.Kind() != reflect.Struct {
  62. return "", fmt.Errorf("query: Values() expects struct input. Got %v", val.Kind())
  63. }
  64. res, err = encodeValue(val, tagOptions{}, 0)
  65. return
  66. }
  67. // encodeValue populates the values parameter from the struct fields in val.
  68. // Embedded structs are followed recursively (using the rules defined in the
  69. // Values function documentation) breadth-first.
  70. func encodeValue(val reflect.Value, opts tagOptions, deep int) (res string, err error) {
  71. typ := val.Type()
  72. switch typ.Kind() {
  73. case reflect.Struct:
  74. return encodeStruct(val, deep+1)
  75. case reflect.Slice, reflect.Array:
  76. return encodeSlice(val, opts, deep+1)
  77. default:
  78. res = valueString(val, opts)
  79. }
  80. return
  81. }
  82. func encodeSlice(val reflect.Value, opts tagOptions, deep int) (res string, err error) {
  83. var del byte = ','
  84. if opts.Contains("comma") {
  85. del = ','
  86. } else if opts.Contains("space") {
  87. del = ' '
  88. } else if opts.Contains("semicolon") {
  89. del = ';'
  90. }
  91. s := new(bytes.Buffer)
  92. first := true
  93. for i := 0; i < val.Len(); i++ {
  94. if first {
  95. first = false
  96. } else {
  97. s.WriteByte(del)
  98. }
  99. var r string
  100. r, err = encodeValue(val.Index(i), opts, deep)
  101. if err != nil {
  102. return
  103. }
  104. s.WriteString(r)
  105. }
  106. return "[" + s.String() + "]", nil
  107. }
  108. func encodeStruct(val reflect.Value, deep int) (res string, err error) {
  109. var values = make(url.Values)
  110. typ := val.Type()
  111. for i := 0; i < typ.NumField(); i++ {
  112. sf := typ.Field(i)
  113. if sf.PkgPath != "" && !sf.Anonymous { // unexported
  114. continue
  115. }
  116. sv := val.Field(i)
  117. tag := sf.Tag.Get("json")
  118. if tag == "-" {
  119. continue
  120. }
  121. name, opts := parseTag(tag)
  122. if opts.Contains("omitempty") && isEmptyValue(sv) {
  123. continue
  124. }
  125. for sv.Kind() == reflect.Ptr {
  126. if sv.IsNil() {
  127. break
  128. }
  129. sv = sv.Elem()
  130. }
  131. var r string
  132. r, err = encodeValue(sv, opts, deep)
  133. if err != nil {
  134. return
  135. }
  136. values.Add(name, r)
  137. }
  138. if deep > 1 {
  139. res = "{" + encode(values) + "}"
  140. } else {
  141. res = encode(values)
  142. }
  143. return res, nil
  144. }
  145. // valueString returns the string representation of a value.
  146. func valueString(v reflect.Value, opts tagOptions) string {
  147. for v.Kind() == reflect.Ptr {
  148. if v.IsNil() {
  149. return ""
  150. }
  151. v = v.Elem()
  152. }
  153. if v.Kind() == reflect.Bool && opts.Contains("int") {
  154. if v.Bool() {
  155. return "1"
  156. }
  157. return "0"
  158. }
  159. if v.Type() == timeType {
  160. t := v.Interface().(time.Time)
  161. if opts.Contains("unix") {
  162. return strconv.FormatInt(t.Unix(), 10)
  163. }
  164. return t.Format(time.RFC3339)
  165. }
  166. return fmt.Sprint(v.Interface())
  167. }
  168. // tagOptions is the string following a comma in a struct field's "url" tag, or
  169. // the empty string. It does not include the leading comma.
  170. type tagOptions []string
  171. // parseTag splits a struct field's url tag into its name and comma-separated
  172. // options.
  173. func parseTag(tag string) (string, tagOptions) {
  174. s := strings.Split(tag, ",")
  175. return s[0], s[1:]
  176. }
  177. // Contains checks whether the tagOptions contains the specified option.
  178. func (o tagOptions) Contains(option string) bool {
  179. for _, s := range o {
  180. if s == option {
  181. return true
  182. }
  183. }
  184. return false
  185. }
  186. func encode(v url.Values) string {
  187. if v == nil {
  188. return ""
  189. }
  190. var buf bytes.Buffer
  191. keys := make([]string, 0, len(v))
  192. for k := range v {
  193. keys = append(keys, k)
  194. }
  195. sort.Strings(keys)
  196. for _, k := range keys {
  197. vs := v[k]
  198. prefix := escape(k) + "="
  199. for _, v := range vs {
  200. if buf.Len() > 0 {
  201. buf.WriteByte('&')
  202. }
  203. buf.WriteString(prefix)
  204. buf.WriteString(escape(v))
  205. }
  206. }
  207. return buf.String()
  208. }
  209. func escape(s string) string {
  210. return s
  211. }
  212. // isEmptyValue checks if a value should be considered empty for the purposes
  213. // of omitting fields with the "omitempty" option.
  214. func isEmptyValue(v reflect.Value) bool {
  215. switch v.Kind() {
  216. case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
  217. return v.Len() == 0
  218. case reflect.Bool:
  219. return !v.Bool()
  220. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  221. return v.Int() == 0
  222. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  223. return v.Uint() == 0
  224. case reflect.Float32, reflect.Float64:
  225. return v.Float() == 0
  226. case reflect.Interface, reflect.Ptr:
  227. return v.IsNil()
  228. }
  229. if v.Type() == timeType {
  230. return v.Interface().(time.Time).IsZero()
  231. }
  232. return false
  233. }