package helper import ( "bytes" "encoding/json" "io" "io/ioutil" "net/http" "time" "github.com/spf13/viper" ) func Url(url string) string { return viper.GetString("service.host.api") + url } // 发送GET请求 // url:请求地址 // response:请求返回的内容 func Get(url string) (response string) { client := http.Client{Timeout: 30 * time.Second} resp, e := client.Get(url) if e != nil { panic(e) } defer resp.Body.Close() var buffer [512]byte result := bytes.NewBuffer(nil) for { n, err := resp.Body.Read(buffer[0:]) result.Write(buffer[0:n]) if err != nil && err == io.EOF { break } else if err != nil { panic(err) } } response = result.String() return } // 发送POST请求 // url:请求地址,data:POST请求提交的数据,contentType:请求体格式,如:application/json // response:请求返回的内容 func Post(url string, data interface{}, header map[string]string) (response string) { jsonStr, _ := json.Marshal(data) req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr)) if err != nil { panic(err) } req.Header.Add("content-type", "application/json") for key := range header { req.Header.Add(key, header[key]) } defer req.Body.Close() client := &http.Client{Timeout: 30 * time.Second} resp, err := client.Do(req) if err != nil { panic(err) } defer resp.Body.Close() result, _ := ioutil.ReadAll(resp.Body) response = string(result) return }