请求
func handle(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "发送的请求的地址是:", r.URL.Path)
fmt.Fprintln(w, "你发送的请求的请求地址后的查询字符串是:", r.URL.RawQuery)
fmt.Fprintln(w, "请求投中的所有信息有:", r.Header)
fmt.Fprintln(w, "请求投中Accept-Encoding的信息是:", r.Header["Accept-Encoding"])
fmt.Fprintln(w, "请求投中Accept-Encoding的信息是:", r.Header.Get("Accept-Encoding"))
// 获取请求体内容的长度
/* len:=r.ContentLength
body := make([]byte,len)
r.Body.Read(body)
//在浏览器中显示请求体中的内容
fmt.Fprint(w,"请求体的内容有",string(body))*/
//解析form表单,在调用r.Form之前必须执行该操作
r.ParseForm()
//获取请求参数
// 如果form表单的action属性的URL地址中也有与form表单参数名相同的请求参数,
// 那么参数值都可以得到,并且form表单中的参数值在URL的参数值前面
//fmt.Println("解析form表单的错误",err)
fmt.Fprintln(w, "请求参数有:", r.Form)
fmt.Fprintln(w, "POST请求的form表单中的请求参数有:", r.PostForm, r.PostFormValue("username"))
fmt.Fprintln(w, "URL中user的请求参数值是", r.FormValue("user"))
fmt.Fprintln(w, "URL中user的请求参数值是", r.FormValue("username"))
}
func main() {
http.HandleFunc("/form", handle)
http.ListenAndServe(":8000", nil)
}
响应--- 返回JSON字符串
// TEST setHead Json
func testHeadJson(w http.ResponseWriter, r *http.Request) {
// 设置响应内容的类型
w.Header().Set("Content-Type", "application/json")
user := User{
Id: 1,
UserName: "pppp",
PassWord: "123465",
}
json, err := json.Marshal(user)
if err != nil {
fmt.Println("JSON 变异错误", err)
}
w.Write(json)
}
响应----重定向
func testRedire(w http.ResponseWriter, r *http.Request) {
// 设置响应头重location 属性
w.Header().Set("Location", "https://www.baidu.com")
//设置响应状态码
w.WriteHeader(302)
}