http 请求相关知识

概述

在 go 语言中 net/http 包用于表述 http 的消息结构,其中 request 用于表述客户端发送的 HTTP 请求消息(请求数据)。

重要的字段 :

URL
Header Body
Form、PostForm、MultipartForm

url 相关

url 数据格式为一个结构体 : 

package main

import (
	"net/http"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		// Path 请求路径
		println(r.URL.Path)
		// RawQuery get 请求参数 ? 后面部分
		println(r.URL.RawQuery)
		w.Write([]byte("hi.."))
	})
	http.ListenAndServe(":80", nil)
}

header 相关

header 数据格式为一个 map :

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, r.Header)
		w.Write([]byte("hi.."))
	})
	http.ListenAndServe(":80", nil)
}

数据示例

[
    Accept:[text/html,application/xhtml+xml,...] 
    Accept-Encoding:[gzip, deflate, br] 
    Accept-Language:[zh-CN,zh;q=0.9] 
    Cache-Control:[max-age=0] 
    Connection:[keep-alive] 
    Sec-Ch-Ua:[" Not A;Brand";v="99", "Chromium";v="102", "Google Chrome";v="102"] 
    Sec-Ch-Ua-Mobile:[?0] 
    Sec-Ch-Ua-Platform:["Windows"] 
    Sec-Fetch-Dest:[document] 
    Sec-Fetch-Mode:[navigate] 
    Sec-Fetch-Site:[none] 
    Sec-Fetch-User:[?1] 
    Upgrade-Insecure-Requests:[1] 
    User-Agent:[Mozilla/5.0 (Windows NT 10.0; Win64...]
]

通过 body 获取请求主体数据

说明 : 可以使用 vscode REST Client 插件 模拟请求

POST  http://localhost/ HTTP/1.1 
Content-Type: application/x-www-form-urlencoded

{
    "name" : "lesscode",
    "age"  : 19
}

接受 body 数据示例

package main

import (
	"fmt"
	"net/http"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		length := r.ContentLength
		body := make([]byte, length)
		r.Body.Read(body)
		fmt.Fprintln(w, string(body))
		w.Write([]byte("hi.."))
	})
	http.ListenAndServe(":80", nil)
}

通过URL Query 接收 get 参数

如 : http://www.***.com/?id=100&name=lesscode

r.URL.RawQuery 会提供实际查询的原始字符串

r.URL.Query(),会提供查询字符串对应的 map[string][]string

package main

import (
	"fmt"
	"net/http"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("Index ..."))
		fmt.Fprintln(w, r.URL.Query())
	})
	http.ListenAndServe(":80", nil)
}