. 1 Package main 2 . 3 Import ( . 4 " encoding / JSON " . 5 " FMT " . 6 " github.com/julienschmidt/httprouter " . 7 " NET / HTTP " . 8 ) . 9 10 // the ResponseWriter three methods is an interface that has the Write WriteHeader Header method parameter response code . 11 FUNC the Hello (http.ResponseWriter W, R & lt * http.Request, P httprouter.Params) { 12 is fmt.Fprintf (W, " Hello,% S \ n- " , p.ByName ( " name ")) 13 } 14 15 //读取请求头 16 func headers(w http.ResponseWriter, r *http.Request) { 17 //map[Accept:[*/*] Accept-Encoding:[gzip, deflate, br] 18 // Cache-Control:[no-cache] Connection:[keep-alive] Content-Length:[42] Content-Type:[text/plain] 19 // Postman-Token:[9d84b4f5-1b43-411a-89c3-fbd9c34d199f] User-Agent:[PostmanRuntime/7.24.0]] 20 h := r.Header 21 fmt.Fprintln(w, h) 22 } 23 24 //表单数据提交 25 func process(w http.ResponseWriter, r *http.Request) { 26 r.ParseForm () 27 fmt.Fprintln (w, r.Form) // the Map [the Hello: [Sau sheong] POST: [456]] 28 // r.PostForm is the only form key-value pairs will not get back the key URL value 29 } 30 31 is FUNC body (http.ResponseWriter W, R & lt * http.Request) { 32 len: = r.ContentLength // Get the data length of the body 33 is body: the make = ([] byte , len) 34 is R & lt. Body.Read (body) 35 fmt.Fprintln (W, len) 36 fmt.Fprintln (W, String (body)) 37 [ } 38 is 39 // the ResponseWriter return json data 40 41 type Post struct { 42 User string 43 Threads []string 44 } 45 46 //向浏览器返回json数据 47 func jsonExample(w http.ResponseWriter, r *http.Request) { 48 w.Header().Set("Content-Type", "application/json") 49 post := &Post{ 50 User: "zhangsan", 51 Threads: []string{"NiHao " , " wohao " }, 52 is } 53 is json, _: = json.Marshal (POST) // Json Marshal: The data is encoded into json string 54 is w.Write (json) 55 } 56 is 57 is // the browser transmitting Cookie 58 FUNC the setCookie (http.ResponseWriter W, R & lt * http.Request) { 59 C1: = http.Cookie { 60 the Name: " first_cookie " , 61 is the Value: " Go the Web Programming " , 62 is the HttpOnly:true, 63 } 64 c2 := http.Cookie{ 65 Name: "second_cookie", 66 Value: "Manning Programming", 67 HttpOnly: true, 68 } 69 //w.Header().Set("Set-Cookie",c1.String()) 70 //w.Header().Add("Set-Cookie",c2.String()) 71 http.SetCookie(w, &c1) 72 http.SetCookie(w, &c2) //三种设置cookie的方法 73 } 74 75 //从浏览器获得cookie 76 func getCookie(w http.ResponseWriter, r *http.Request) { 77 h := r.Header["Cookie"] 78 cs := r.Cookies() 79 fmt.Fprintln(w, h) 80 fmt.Fprintln(w, cs) 81 } 82 83 func main() { 84 //mux:=httprouter.New() 85 //mux.GET("/hello/:name",Hello) 86 //log.Fatal(http.ListenAndServe(":8080",mux)) 87 // 88 //http.HandleFunc("/header",headers) 89 //http.HandleFunc("/body",body) 90 //http.HandleFunc("/process",process) 91 //http.HandleFunc("/json",jsonExample) 92 http.HandleFunc("/setcookie", setCookie) 93 http.HandleFunc("/getcookie", getCookie) 94 95 http.ListenAndServe(":8080", nil) 96 97 }