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}} |
| 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" |
| |
| |
| headers := make(map[string]string) |
| |
| |
| |
| 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}} |
| 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 := []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 |
| } |
| |
| |
| 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}} |
| 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 |
| } |

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了