whiteList_test.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package http
  2. import (
  3. "crypto/md5"
  4. "encoding/hex"
  5. "flag"
  6. "fmt"
  7. "go-common/app/admin/main/creative/conf"
  8. "io/ioutil"
  9. "net/http"
  10. "net/url"
  11. "path/filepath"
  12. "strconv"
  13. "strings"
  14. "testing"
  15. "time"
  16. . "github.com/smartystreets/goconvey/convey"
  17. )
  18. const (
  19. _host = "http://0.0.0.0:6344"
  20. )
  21. var (
  22. _view = _host + "/x/admin/creative/whitelist/view"
  23. )
  24. func init() {
  25. dir, _ := filepath.Abs("../cmd/creative-admin.toml")
  26. flag.Set("conf", dir)
  27. conf.Init()
  28. }
  29. // Sign fn
  30. func Sign(params url.Values) (query string, err error) {
  31. if len(params) == 0 {
  32. return
  33. }
  34. if params.Get("appkey") == "" {
  35. err = fmt.Errorf("utils http get must have parameter appkey")
  36. return
  37. }
  38. if params.Get("appsecret") == "" {
  39. err = fmt.Errorf("utils http get must have parameter appsecret")
  40. return
  41. }
  42. if params.Get("sign") != "" {
  43. err = fmt.Errorf("utils http get must have not parameter sign")
  44. return
  45. }
  46. // sign
  47. secret := params.Get("appsecret")
  48. params.Del("appsecret")
  49. tmp := params.Encode()
  50. if strings.IndexByte(tmp, '+') > -1 {
  51. tmp = strings.Replace(tmp, "+", "%20", -1)
  52. }
  53. mh := md5.Sum([]byte(tmp + secret))
  54. params.Set("sign", hex.EncodeToString(mh[:]))
  55. query = params.Encode()
  56. return
  57. }
  58. func Test_View(t *testing.T) {
  59. Convey("View", t, func() {
  60. params := url.Values{}
  61. params.Set("id", "7")
  62. params.Set("appkey", conf.Conf.App.Key)
  63. params.Set("appsecret", conf.Conf.App.Secret)
  64. params.Set("ts", strconv.FormatInt(time.Now().Unix(), 10))
  65. var (
  66. query, _ = Sign(params)
  67. url string
  68. )
  69. url = _view + "?" + query
  70. body, err := oget(url)
  71. So(err, ShouldBeNil)
  72. So(body, ShouldNotBeNil)
  73. So(err, ShouldBeNil)
  74. })
  75. }
  76. // oget http get request
  77. func oget(url string) (body []byte, err error) {
  78. resp, err := http.Get(url)
  79. if err != nil {
  80. return
  81. }
  82. defer resp.Body.Close()
  83. body, err = ioutil.ReadAll(resp.Body)
  84. return
  85. }