常用的GET、POST请求方式(带参数及请求头)

1,594 阅读1分钟

最近在工作中发现Golang常用的GET、POST请求方式网上写的比较模糊。在这篇文章记录一下较为完整的GET、POST请求方式(带参数及请求头)。

1. 先创建一个解析请求的服务

这边使用的是Gin框架来创建解析请求服务。

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
)

func main() {
	router := gin.Default()
	router.POST("/post", PostFunc)
	router.GET("/get", GetFunc)
	router.Run(":5000")
}

func GetFunc(c *gin.Context) {
	name := c.Query("name")
	age := c.Query("age")
	uri:=c.Request.URL.RawQuery
	fmt.Println(name)
	fmt.Println(age)
	fmt.Println(uri)
}

func PostFunc(c *gin.Context) {
	buf := make([]byte, 1024)
	n, _ := c.Request.Body.Read(buf)
	fmt.Println(string(buf[0:n]))
}


2. 常用的GET、POST请求

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"unsafe"
)

func main() {
	fmt.Println(getReq("zhangsan", "18"))
	postReq("lisi", 19)
	postReqJson1()
	var j JsonPost
	(*JsonPost).postReqJson2(&j)  // 隐式调用
	
}

func getReq(name string, age string) string {
	client := &http.Client{}

	req, err := http.NewRequest("GET", "http://localhost:5000/get",
		nil)
	if err != nil {
		panic(err)
	}
	query := req.URL.Query()
	query.Add("name", name)
	query.Add("age", age)
	req.URL.RawQuery = query.Encode()

	resp, err := client.Do(req)

	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		panic(err)
	}

	resdata := string(body)
	return resdata

}

func postReq(name string, age int) {
	client := &http.Client{}

	req, err := http.NewRequest("POST", "http://localhost:5000/post",
		strings.NewReader(fmt.Sprintf("name=%s&age=%d", name, age)))
	if err != nil {
		panic(err)
	}

	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	resp, err := client.Do(req)

	defer resp.Body.Close()

}

// 通过json提交post
func postReqJson1() {
	url := "http://localhost:5000/post"
	name := "wangwu"
	age := 20

	//json序列化
	post := fmt.Sprintf("{\"name\":%s,\"age\":%d}", name, age)
	fmt.Println(url, "post", post)

	var jsonStr = []byte(post)

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))

	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	fmt.Println("status", resp.Status)
	fmt.Println("response:", resp.Header)
	body, _ := ioutil.ReadAll(resp.Body)
	fmt.Println("response Body:", string(body))

}

type JsonPost struct {
}

func (jp *JsonPost) postReqJson2() {
	post := make(map[string]interface{})
	post["name"] = "王柳"
	post["age"] = 21
	bytesData, err := json.Marshal(post)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	reader := bytes.NewReader(bytesData)
	url := "http://localhost:5000/post"
	request, err := http.NewRequest("POST", url, reader)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	client := http.Client{}
	resp, err := client.Do(request)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	//byte数组直接转成string,优化内存
	str := (*string)(unsafe.Pointer(&respBytes))
	fmt.Println(*str)

}