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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM