請求
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)
}