Go语言http之请求接收和处理 代码

 1 package main
 2 
 3 import (
 4     "encoding/json"
 5     "fmt"
 6     "github.com/julienschmidt/httprouter"
 7     "net/http"
 8 )
 9 
10 //ResponseWriter是一个接口 拥有三个方法 Write WriteHeader的参数为响应码 Header方法
11 func Hello(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
12     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) //map[hello:[sau sheong] post:[456]]
28     //r.PostForm 是只获取表单键值对 不会回去URL键值对
29 }
30 
31 func body(w http.ResponseWriter, r *http.Request) {
32     len := r.ContentLength //获取主体数据的长度
33     body := make([]byte, len)
34     r.Body.Read(body)
35     fmt.Fprintln(w, len)
36     fmt.Fprintln(w, string(body))
37 }
38 
39 //ResponseWriter返回json数据
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     }
53     json, _ := json.Marshal(post) //Json Marshal:将数据编码成json字符串
54     w.Write(json)
55 }
56 
57 //向浏览器发送cookie
58 func setCookie(w http.ResponseWriter, r *http.Request) {
59     c1 := http.Cookie{
60         Name:     "first_cookie",
61         Value:    "Go Web Programming",
62         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 }

猜你喜欢

转载自www.cnblogs.com/yh2924/p/12598184.html