Files
servicebase/pkg/helper/NetHelper.go
2025-11-19 14:24:13 +08:00

69 lines
1.4 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 any, 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
}