package http import ( "bytes" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "time" "kpt.xdmy/apiserver/config" "kpt.xdmy/pkg/log" ) type Auth struct { Username string Password string } type Client struct { client *http.Client sapAuth *Auth srmAuth *Auth } func NewClient(con *config.Config) *Client { return &Client{ client: &http.Client{ Timeout: con.Http.TimeOut * time.Second, }, sapAuth: &Auth{ Username: con.Http.SapName, Password: con.Http.SapPwd, }, srmAuth: &Auth{ Username: con.Http.SrmName, Password: con.Http.SrmPwd, }, } } func JsonMarshal(p interface{}) (r io.Reader, err error) { if p == nil { return } var b []byte switch p.(type) { case string: b = []byte(p.(string)) case []byte: b = p.([]byte) default: b, err = json.Marshal(p) if err != nil { err = log.Error("failed to marshal", err, p) return } } r = bytes.NewBuffer(b) return } func (c *Client) NewRequest(method, url string, body interface{}) (req *http.Request, err error) { byteBody, e := JsonMarshal(body) if e != nil { err = e return } req, err = http.NewRequest(method, url, byteBody) if err != nil { err = log.Error("http newRequest ", err, url, body) return } if method != http.MethodGet { req.Header.Add("Content-Type", "application/json") } return } func (c *Client) Do(req *http.Request, res interface{}) (err error) { resp, e := c.client.Do(req) if e != nil { err = log.Error("http do ", e, req.URL, req.Body) return } defer resp.Body.Close() bodyRes, err := ioutil.ReadAll(resp.Body) err = json.Unmarshal(bodyRes, &res) // err = json.NewDecoder(resp.Body).Decode(res) if err != nil { err = log.Error("http decode ", e, req.URL, req.Body, resp.StatusCode) return } return } func (c *Client) SetBasicAuth(req *http.Request) { fmt.Println(c.sapAuth.Username, c.sapAuth.Password, "aaa") req.SetBasicAuth(c.sapAuth.Username, c.sapAuth.Password) } func (c *Client) SetSrmBasicAuth(req *http.Request) { req.SetBasicAuth(c.srmAuth.Username, c.srmAuth.Password) }