1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- package http
- import (
- "bytes"
- "encoding/json"
- "io"
- "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
- }
- 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,
- },
- }
- }
- 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()
- 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) {
- req.SetBasicAuth(c.sapAuth.Username, c.sapAuth.Password)
- }
|