0efaa6b0e1e93ee3a2404a479775f6ac0d50fe09.svn-base 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package transport
  2. import (
  3. "encoding/json"
  4. "flag"
  5. "net/http"
  6. "net/url"
  7. "strings"
  8. "testing"
  9. "time"
  10. )
  11. /**
  12. * @Author : dixuanhuang
  13. * @File : http_test.go
  14. * @Date : 2020/8/4 11:26 上午
  15. * @Description:
  16. **/
  17. func TestRegister(t *testing.T) {
  18. if !flag.Parsed(){
  19. flag.Parse()
  20. }
  21. args := flag.Args()
  22. postUrl := "http://127.0.0.1:30036/register"
  23. if len(args) > 0{
  24. postUrl = args[0]
  25. }
  26. body := map[string]string{
  27. "email":"aoho1@mail.com",
  28. "password":"aoho",
  29. "username": "aoho",
  30. }
  31. result, err := httpPost(postUrl, body)
  32. if err != nil{
  33. t.Errorf("http post err %s", err)
  34. t.FailNow()
  35. }
  36. t.Logf("result is %v", result)
  37. }
  38. func TestLogin(t *testing.T) {
  39. if !flag.Parsed(){
  40. flag.Parse()
  41. }
  42. args := flag.Args()
  43. postUrl := "http://127.0.0.1:30036/login"
  44. if len(args) > 0{
  45. postUrl = args[0]
  46. }
  47. body := map[string]string{
  48. "email":"aoho@mail.com",
  49. "password":"aoho1",
  50. }
  51. result, err := httpPost(postUrl, body)
  52. if err != nil{
  53. t.Errorf("http post err %s", err)
  54. t.FailNow()
  55. }
  56. t.Logf("result is %v", result)
  57. }
  58. func httpPost(postUrl string, body map[string]string) (interface{}, error) {
  59. // 超时时间:5秒
  60. client := &http.Client{Timeout: 5 * time.Second}
  61. dataUrlVal := url.Values{}
  62. for k, v := range body {
  63. dataUrlVal.Add(k, v)
  64. }
  65. req,err := http.NewRequest("POST", postUrl, strings.NewReader(dataUrlVal.Encode()))
  66. if err != nil{
  67. return nil, err
  68. }
  69. req.Header.Add("Content-Type","application/x-www-form-urlencoded")
  70. //提交请求
  71. resp, err := client.Do(req)
  72. if err != nil{
  73. return nil, err
  74. }
  75. defer resp.Body.Close()
  76. //读取返回值
  77. decode := json.NewDecoder(resp.Body)
  78. var result interface{}
  79. err = decode.Decode(&result)
  80. if err != nil{
  81. return nil, err
  82. }
  83. return result, nil
  84. }