net/http包实战
目录
1. Post调用http/https接口
1.1 调用后返回 json
写好的调用函数
func PostJSONWithResp(url string, headers map[string]string, data interface{}, timeout time.Duration) (statusCode int, respBody []byte, err error) {
var jsonBytes []byte
if bytes, ok := data.([]byte); ok {
jsonBytes = bytes
} else {
if jsonBytes, err = json.Marshal(data); err != nil {
return
}
}
var req *http.Request
if req, err = http.NewRequest("POST", url, bytes.NewBuffer(jsonBytes)); err != nil {
return
}
req.Header.Set("Content-Type", "application/json")
if headers != nil {
for key, value := range headers {
req.Header.Set(key, value)
}
}
tr:=&http.Transport{TLSClientConfig:&tls.Config{InsecureSkipVerify:true}} //不验证ca证书,否则卡在这里
client := &http.Client{Timeout: timeout,Transport:tr}
resp, err := client.Do(req)
if err != nil {
return
}
defer resp.Body.Close()
statusCode = resp.StatusCode
respBody, _ = ioutil.ReadAll(resp.Body)
return
}
完整示例(调用smart-x示例)
package main
import (
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
)
func main() {
//定义一个结构体传参
var body struct {
UserName string `json:"username"`
Password string `json:"password"`
}
body.UserName = "liubei"
body.Password = "3xxxxxxx"
//定义harder,Content-Type后边函数里写了,这里不用写,定义空即可。
headers := make(map[string]string)
//headers["Content-Type"] = "application/json"
//调用PostJSONWithResp函数,得到返回值
statusCode,respBody,_ := PostJSONWithResp("https://10.10.xxx.159/api/v3/sessions",headers,
body,
time.Duration(time.Second*10))
fmt.Println(statusCode,string(respBody))
}
func PostJSONWithResp(url string, headers map[string]string, data interface{}, timeout time.Duration) (statusCode int, respBody []byte, err error) {
var jsonBytes []byte
if bytes, ok := data.([]byte); ok {
jsonBytes = bytes
} else {
if jsonBytes, err = json.Marshal(data); err != nil {
return
}
}
var req *http.Request
if req, err = http.NewRequest("POST", url, bytes.NewBuffer(jsonBytes)); err != nil {
return
}
req.Header.Set("Content-Type", "application/json")
if headers != nil {
for key, value := range headers {
req.Header.Set(key, value)
}
}
tr:=&http.Transport{TLSClientConfig:&tls.Config{InsecureSkipVerify:true}} //不验证ca证书,否则卡在这里
client := &http.Client{Timeout: timeout,Transport:tr}
resp, err := client.Do(req)
if err != nil {
return
}
defer resp.Body.Close()
statusCode = resp.StatusCode
respBody, _ = ioutil.ReadAll(resp.Body)
return
}
- 返回结果
200 {"user_id":"169f95ca-7899-4cb4-ace7-b7484d33901c","token":"xxxxxx","create_time":"2022-03-01T08:42:52.418108628Z","expire_time":"2022-03-08T08:42:52.418108825Z"}
- body也可以用json定义
body := []byte(`{"username":"liuwei","password":"30gmcyt8Kllyhy"}`)
调用jfrog示例
package crowJfrog
import (
"encoding/json"
"fmt"
"time"
)
type JfrogRepository struct {
Type string `json:"type"`
TypeSpecific struct {
LocalChecksumPolicy string `json:"localChecksumPolicy"`
RepoType string `json:"repoType"`
Icon string `json:"icon"`
Text string `json:"text"`
ListRemoteFolderItems bool `json:"listRemoteFolderItems"`
Url string `json:"url"`
} `json:"typeSpecific"`
Advanced struct {
Cache struct {
KeepUnusedArtifactsHours string `json:"keepUnusedArtifactsHours"`
RetrievalCachePeriodSecs int `json:"retrievalCachePeriodSecs"`
AssumedOfflineLimitSecs int `json:"assumedOfflineLimitSecs"`
MissedRetrievalCachePeriodSecs int `json:"missedRetrievalCachePeriodSecs"`
} `json:"cache"`
Network struct {
SocketTimeout int `json:"socketTimeout"`
SyncProperties bool `json:"syncProperties"`
LenientHostAuth bool `json:"lenientHostAuth"`
CookieManagement bool `json:"cookieManagement"`
} `json:"network"`
BlackedOut bool `json:"blackedOut"`
AllowContentBrowsing bool `json:"allowContentBrowsing"`
} `json:"advanced"`
Basic struct {
IncludesPattern string `json:"includesPattern"`
IncludesPatternArray []string `json:"includesPatternArray"`
ExcludesPatternArray []interface{} `json:"excludesPatternArray"`
Layout string `json:"layout"`
PublicDescription string `json:"publicDescription"`
InternalDescription string `json:"internalDescription"`
} `json:"basic"`
General struct {
RepoKey string `json:"repoKey"`
} `json:"general"`
}
func CreateJfrogRepository(jfrogRepository JfrogRepository)error {
buf, _ := json.MarshalIndent(jfrogRepository, "", " ")
fmt.Println( string(buf))
headers := make(map[string]string)
headers["Authorization"] = "Basic YWRtaW46MVxxxxxxx"
url := "http://jfrogcto.xxx.com.cn:8081/artifactory/ui/admin/repositories"
_,_,err := PostJSONWithResp(url,headers,
jfrogRepository,
time.Duration(time.Second*10))
if err != nil {
return err
}
return nil
}
//利用上边的创建函数创建一个简单的jfrog库
func CreateSimpleJfrogRepository(repositoryName string,publicDescription string)error{
var jfrogRepository JfrogRepository
jfrogRepository.Type = "localRepoConfig"
jfrogRepository.TypeSpecific.RepoType = "Generic"
jfrogRepository.TypeSpecific.LocalChecksumPolicy = "CLIENT"
jfrogRepository.TypeSpecific.Icon = "generic"
jfrogRepository.TypeSpecific.Text = "Generic"
jfrogRepository.TypeSpecific.ListRemoteFolderItems = true
jfrogRepository.Advanced.Cache.RetrievalCachePeriodSecs = 7200
jfrogRepository.Advanced.Cache.AssumedOfflineLimitSecs = 300
jfrogRepository.Advanced.Cache.MissedRetrievalCachePeriodSecs = 1800
jfrogRepository.Advanced.Network.SocketTimeout = 15000
jfrogRepository.Basic.IncludesPattern = "**/*"
jfrogRepository.Basic.ExcludesPatternArray = make([]interface{},1)
jfrogRepository.Basic.ExcludesPatternArray[0] = "**/*"
jfrogRepository.Basic.Layout = "simple-default"
jfrogRepository.Basic.PublicDescription = publicDescription
jfrogRepository.Basic.InternalDescription = repositoryName
jfrogRepository.General.RepoKey = repositoryName
err := CreateJfrogRepository(jfrogRepository)
if err != nil {
return err
}
return nil
}
1.2 调用后只返回code
func PostJSON(url string, headers map[string]string, data interface{}, timeout time.Duration) (statusCode int, err error) {
logger.Debugf("[httputils] PostJSON url: %s", url)
var jsonBytes []byte
if bytes, ok := data.([]byte); ok {
jsonBytes = bytes
} else {
if jsonBytes, err = json.Marshal(data); err != nil {
return
}
}
logger.Debugf("[httputils] post data: %s", string(jsonBytes))
var req *http.Request
if req, err = http.NewRequest("POST", url, bytes.NewBuffer(jsonBytes)); err != nil {
return
}
req.Header.Set("Content-Type", "application/json")
if headers != nil {
for key, value := range headers {
req.Header.Set(key, value)
}
}
client := &http.Client{Timeout: timeout}
resp, err := client.Do(req)
if err != nil {
return
}
statusCode = resp.StatusCode
return
}
2. Get 调用https接口
func GetJSON(url string, headers map[string]string, timeout time.Duration) (respBody []byte, err error) {
logger.Debugf("[HttpServer] GetJSON : %s", url)
client := &http.Client{Timeout: timeout}
req, err := http.NewRequest("GET", url, nil)
if headers != nil {
for key, value := range headers {
req.Header.Set(key, value)
}
}
var resp *http.Response
resp, err = client.Do(req)
if err == nil {
defer resp.Body.Close()
respBody, err = ioutil.ReadAll(resp.Body)
}
return
}
3. Put调用https接口
func PutJSONWithResp(url string, headers map[string]string, data interface{}, timeout time.Duration) (statusCode int, respBody []byte, err error) {
var jsonBytes []byte
if bytes, ok := data.([]byte); ok {
jsonBytes = bytes
} else {
if jsonBytes, err = json.Marshal(data); err != nil {
return
}
}
var req *http.Request
if req, err = http.NewRequest("PUT", url, bytes.NewBuffer(jsonBytes)); err != nil {
return
}
req.Header.Set("Content-Type", "application/json")
if headers != nil {
for key, value := range headers {
req.Header.Set(key, value)
}
}
tr:=&http.Transport{TLSClientConfig:&tls.Config{InsecureSkipVerify:true}} //不验证ca证书,否则卡在这里
client := &http.Client{Timeout: timeout,Transport:tr}
resp, err := client.Do(req)
if err != nil {
return
}
defer resp.Body.Close()
statusCode = resp.StatusCode
respBody, _ = ioutil.ReadAll(resp.Body)
return
}