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生成代碼後自己改造下
在這裏插入圖片描述
在這裏插入圖片描述

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