http.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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. }
  22. func NewClient(con *config.Config) *Client {
  23. return &Client{
  24. client: &http.Client{
  25. Timeout: con.Http.TimeOut * time.Second,
  26. },
  27. sapAuth: &Auth{
  28. Username: con.Http.SapName,
  29. Password: con.Http.SapPwd,
  30. },
  31. srmAuth: &Auth{
  32. Username: con.Http.SrmName,
  33. Password: con.Http.SrmPwd,
  34. },
  35. }
  36. }
  37. func JsonMarshal(p interface{}) (r io.Reader, err error) {
  38. if p == nil {
  39. return
  40. }
  41. var b []byte
  42. switch p.(type) {
  43. case string:
  44. b = []byte(p.(string))
  45. case []byte:
  46. b = p.([]byte)
  47. default:
  48. b, err = json.Marshal(p)
  49. if err != nil {
  50. err = log.Error("failed to marshal", err, p)
  51. return
  52. }
  53. }
  54. r = bytes.NewBuffer(b)
  55. return
  56. }
  57. func (c *Client) NewRequest(method, url string, body interface{}) (req *http.Request, err error) {
  58. byteBody, e := JsonMarshal(body)
  59. if e != nil {
  60. err = e
  61. return
  62. }
  63. req, err = http.NewRequest(method, url, byteBody)
  64. if err != nil {
  65. err = log.Error("http newRequest ", err, url, body)
  66. return
  67. }
  68. if method != http.MethodGet {
  69. req.Header.Add("Content-Type", "application/json")
  70. }
  71. return
  72. }
  73. func (c *Client) Do(req *http.Request, res interface{}) (err error) {
  74. resp, e := c.client.Do(req)
  75. if e != nil {
  76. err = log.Error("http do ", e, req.URL, req.Body)
  77. return
  78. }
  79. defer resp.Body.Close()
  80. bodyRes, err := ioutil.ReadAll(resp.Body)
  81. err = json.Unmarshal(bodyRes, &res)
  82. // err = json.NewDecoder(resp.Body).Decode(res)
  83. if err != nil {
  84. err = log.Error("http decode ", e, req.URL, req.Body, resp.StatusCode)
  85. return
  86. }
  87. return
  88. }
  89. func (c *Client) SetBasicAuth(req *http.Request) {
  90. fmt.Println(c.sapAuth.Username, c.sapAuth.Password, "aaa")
  91. req.SetBasicAuth(c.sapAuth.Username, c.sapAuth.Password)
  92. }
  93. func (c *Client) SetSrmBasicAuth(req *http.Request) {
  94. req.SetBasicAuth(c.srmAuth.Username, c.srmAuth.Password)
  95. }