github.com/OrigamiWang/msd/micro@v0.0.0-20240229032328-b62246268db9/framework/client/client.go (about) 1 package client 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "fmt" 7 "io" 8 "net/http" 9 "strings" 10 11 "github.com/OrigamiWang/msd/micro/auth/tls" 12 logutil "github.com/OrigamiWang/msd/micro/util/log" 13 ) 14 15 var ( 16 HC *HttpClient 17 ) 18 19 type HttpClient struct { 20 Client *http.Client 21 } 22 23 func init() { 24 HC = &HttpClient{ 25 Client: &http.Client{ 26 Transport: &http.Transport{ 27 TLSClientConfig: tls.TlsClientConfig, 28 }, 29 }, 30 } 31 } 32 33 // RequestWithHead is a shortcut of func(hc *HttpClient) RequestWithHead(){} 34 func RequestWithHead(method, host, uri string, header http.Header, param interface{}) (interface{}, error) { 35 return HC.RequestWithHead(method, host, uri, header, param) 36 } 37 38 func getBytes(data interface{}) (result []byte, err error) { 39 if data == nil { 40 return nil, nil 41 } 42 43 switch v := data.(type) { 44 case string: 45 result = []byte(v) 46 case []byte: 47 result = v 48 default: 49 result, err = json.Marshal(data) 50 } 51 return 52 } 53 54 func do(method, url string, header http.Header, param interface{}) (interface{}, error) { 55 var err error 56 requestBody, err := getBytes(param) 57 if err != nil { 58 logutil.Error("ready to post to [%v], data: [%+v]", url, param) 59 return nil, err 60 } 61 62 req, err := http.NewRequest(method, url, bytes.NewBuffer(requestBody)) 63 if err != nil { 64 logutil.Error("creat request failed") 65 return nil, err 66 } 67 req.Header = header 68 resp, err := HC.Client.Do(req) 69 if err != nil { 70 logutil.Error("client do request failed") 71 return nil, err 72 } 73 body, err := io.ReadAll(resp.Body) 74 if err != nil { 75 logutil.Error("read resp.Body failed, err: %v", err) 76 return nil, err 77 } 78 defer resp.Body.Close() 79 var result map[string]interface{} 80 err = json.Unmarshal(body, &result) 81 if err != nil { 82 logutil.Error("unmarshal response to struct failed, err: %v", err) 83 } 84 return result, nil 85 } 86 func (hc *HttpClient) RequestWithHead(method, host, uri string, header http.Header, param interface{}) (interface{}, error) { 87 logutil.Info("ready to post to host: %v, uri: %v", host, uri) 88 url := host + uri 89 if !strings.HasPrefix(url, "http://") || !strings.HasPrefix(url, "https://") { 90 url = fmt.Sprintf("https://%s", url) 91 } 92 return do(method, url, header, param) 93 }