Golang发送HTTP请求

Golang发送HTTP请求

import (
	"bytes"
	"encoding/json"
	"errors"
	"io"
	"io/ioutil"
	"net/http"

	"github.com/golang/glog"
)

// AuthResp 授权码返回结构
type AuthResp struct {
	Token string `json:"token"`
}

// GetAuthHeader 获取auth header
func GetAuthHeader() (header map[string]string, err error) {
	// 1、获取授权码
	auth, err := getAuthorization()
	if err != nil {
		glog.Errorf("getAuthorization failed, err=%v", err)
		return
	}
	// 2、生成header
	header = map[string]string{
		"Authorization": auth,
	}
	return
}

// getAuthorization 获取授权码
func getAuthorization() (auth string, err error) {
	// 1、构建需要的参数
	data := map[string]string{
		"username": "username",
		"password": "password",
	}
	jsonData, err := json.Marshal(data)
	if err != nil {
		return
	}

	// 2、请求获取授权码
	resp, err := sendRequest("https://ip:port/auth", bytes.NewReader(jsonData), nil, "POST")
	if err != nil {
		glog.Errorf("sendRequest failed, err=%v", err)
		return
	}

	// 3、从结果中获取token
	authResp := AuthResp{}
	err = json.Unmarshal(resp, &authResp)
	if err != nil {
		return
	}
	auth = authResp.Token
	return
}

// sendRequest 发送request
func sendRequest(url string, body io.Reader, addHeaders map[string]string, method string) (resp []byte, err error) {
	// 1、创建req
	req, err := http.NewRequest(method, url, body)
	if err != nil {
		return
	}
	req.Header.Add("Content-Type", "application/json")

	// 2、设置headers
	if len(addHeaders) > 0 {
		for k, v := range addHeaders {
			req.Header.Add(k, v)
		}
	}

	// 3、发送http请求
	client := &http.Client{}
	response, err := client.Do(req)
	if err != nil {
		return
	}
	defer response.Body.Close()

	if response.StatusCode != 200 {
		err = errors.New("http status err")
		glog.Errorf("sendRequest failed, url=%v, response status code=%d", url, response.StatusCode)
		return
	}

	// 4、结果读取
	resp, err = ioutil.ReadAll(response.Body)
	return
}

Postman生成代码

也可用postman生成代码后自己改造下
在这里插入图片描述
在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章