golong 调用http/https接口,使用net/http包写好的几个函数

net/http包的使用可参考文档 《golang的net/http包Client的使用》

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
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

玄德公笔记

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值