You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
jcook-sdk/util/http/http.go

67 lines
1.2 KiB

3 years ago
package http
import (
"bytes"
"fmt"
"io"
"net/http"
"net/url"
)
var (
client = &http.Client{}
)
func init() {
}
func FormatUrl(endPoint string, isHttps bool) string {
if isHttps {
return fmt.Sprintf("https://%s", endPoint)
} else {
return fmt.Sprintf("http://%s", endPoint)
}
}
func JGet(url string, params url.Values, header map[string]string) ([]byte, error) {
req, _ := http.NewRequest("GET", url, nil)
for k, v := range header {
req.Header.Add(k, v)
}
req.URL.RawQuery = params.Encode()
resp, err := client.Do(req)
if err != nil {
return []byte(""), err
}
defer func(Body io.ReadCloser) {
err = Body.Close()
if err != nil {
fmt.Println(err.Error())
}
}(resp.Body)
return io.ReadAll(resp.Body)
}
func JPostJson(url string, jsonStr []byte, header map[string]string) ([]byte, error) {
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
req.Header.Set("Content-Type", "application/json")
for k, v := range header {
req.Header.Add(k, v)
}
resp, err := client.Do(req)
if err != nil {
return []byte(""), err
}
defer func(Body io.ReadCloser) {
err = Body.Close()
if err != nil {
fmt.Println(err.Error())
}
}(resp.Body)
return io.ReadAll(resp.Body)
}