http.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. package http
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "net/http"
  9. "time"
  10. "kpt.xdmy/apiserver/config"
  11. "kpt.xdmy/pkg/log"
  12. )
  13. type Auth struct {
  14. Username string
  15. Password string
  16. }
  17. type Client struct {
  18. client *http.Client
  19. sapAuth *Auth
  20. srmAuth *Auth
  21. Liugong *config.LiuGong
  22. }
  23. func NewClient(con *config.Config) *Client {
  24. return &Client{
  25. client: &http.Client{
  26. Timeout: con.Http.TimeOut * time.Second,
  27. },
  28. sapAuth: &Auth{
  29. Username: con.Http.SapName,
  30. Password: con.Http.SapPwd,
  31. },
  32. srmAuth: &Auth{
  33. Username: con.Http.SrmName,
  34. Password: con.Http.SrmPwd,
  35. },
  36. Liugong: &config.LiuGong{
  37. UserName: con.LiuGong.UserName,
  38. PassWord: con.LiuGong.PassWord,
  39. Routing: con.LiuGong.Routing,
  40. },
  41. }
  42. }
  43. func JsonMarshal(p interface{}) (r io.Reader, err error) {
  44. if p == nil {
  45. return
  46. }
  47. var b []byte
  48. switch p.(type) {
  49. case string:
  50. b = []byte(p.(string))
  51. case []byte:
  52. b = p.([]byte)
  53. default:
  54. b, err = json.Marshal(p)
  55. if err != nil {
  56. err = log.Error("failed to marshal", err, p)
  57. return
  58. }
  59. }
  60. r = bytes.NewBuffer(b)
  61. return
  62. }
  63. func (c *Client) NewRequest(method, url string, body interface{}) (req *http.Request, err error) {
  64. byteBody, e := JsonMarshal(body)
  65. if e != nil {
  66. err = e
  67. return
  68. }
  69. req, err = http.NewRequest(method, url, byteBody)
  70. if err != nil {
  71. err = log.Error("http newRequest ", err, url, body)
  72. return
  73. }
  74. if method != http.MethodGet {
  75. req.Header.Add("Content-Type", "application/json")
  76. }
  77. return
  78. }
  79. func (c *Client) Do(req *http.Request, res interface{}) (err error) {
  80. resp, e := c.client.Do(req)
  81. if e != nil {
  82. err = log.Error("http do ", e, req.URL, req.Body)
  83. return
  84. }
  85. defer resp.Body.Close()
  86. bodyRes, err := ioutil.ReadAll(resp.Body)
  87. err = json.Unmarshal(bodyRes, &res)
  88. if err != nil {
  89. err = log.Error("http decode ", e, req.URL, req.Body, resp.StatusCode)
  90. return
  91. }
  92. return
  93. }
  94. func (c *Client) SetBasicAuth(req *http.Request) {
  95. fmt.Println(c.sapAuth.Username, c.sapAuth.Password, "aaa")
  96. req.SetBasicAuth(c.sapAuth.Username, c.sapAuth.Password)
  97. }
  98. func (c *Client) SetSrmBasicAuth(req *http.Request) {
  99. req.SetBasicAuth(c.srmAuth.Username, c.srmAuth.Password)
  100. }