http.go 1.7 KB

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