golang handles post, get request and string to json format conversion

1. POST request

package main

import (
  "bytes"
  "net/http"
  "io/ioutil"
)

type getToken struct{
    
      // 用于将string格式转成json格式,取出token
	Token string `json:"token"`
}

// 处理post请求
func GetToken() string {
    
      
	jsonStr :=[]byte(`{ "username": "xxx", "password": "xxx" }`)  // 请求时需要带的参数
	url:= "url"  // 请求的url
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))  // 发起请求,没有参数时,可将bytes.NewBuffer(jsonStr)改为nil
	req.Header.Add("Content-Type", "application/json") // 发起请求时需要的头信息
	rst.Header.Add("AUTHORIZATION", token)  // 发起请求时需要的头信息,需要多个时,可继续往后面加 

	client := &http.Client{
    
    }  // 处理返回结果
	resp, err := client.Do(req)
	if err != nil {
    
    
		// handle error
	}
	defer resp.Body.Close()
	var tokenJson getToken  // 定义一个结构体,用来将结果的string格式转成json格式,便于对请求结果进行处理
	body, _ := ioutil.ReadAll(resp.Body)  // 读取请求结果
	tokenGet := string(body)  // 请求结果string格式
	errJson := json.Unmarshal([]byte(tokenGet), &tokenJson)  // 将string 格式转成json格式
	if errJson != nil {
    
    
		initlog.Error.Println(errJson)  // 错误写进日志文件
	}
	return tokenJson.Token  // 所需要的请求结果token
}

Note: The structure getToken defined by the above code is used to convert the requested string format into a convenient json format. The first letter of the element name in the structure must be capitalized! Otherwise it is easy to pit!

2. Get request is the same as post, just change the method in http.NewRequest() to GET, there is no code here

Guess you like

Origin blog.csdn.net/weixin_43202081/article/details/108727988