http:無狀態協議,是互聯網中使用http使用http實現計算機和計算機之間的請求和響應
使用純文本方式發送和接受協議數據,不需要借助專門工具進行分析就知道協議中的數據
服務器端的幾個概念
-
Request:用戶請求的信息,用來解析用戶的請求信息,包括 post、get、cookie、url 等信息
-
Response:服務器需要反饋給客戶端的信息
-
Conn:用戶的每次請求鏈接
-
Handler:處理請求和生成返回信息的處理邏輯
http報文的組成
- 請求行
- 請求頭
- 請求體
- 響應頭
- 響應體
多種請求方式:
- GET:向服務器請求資源地址
- POST:直接返回請求內容
- HEAD:只要求響應頭
- PUT:創建資源
- DELETE:刪除資源
- TRACE:返回請求本身
- OPTIONS:返回服務器支持HTTP方法列表、
- CONNECT:建立網絡連接
- PATCH :修改資源
軟件模型
- B/S結構,客戶端瀏覽器/服務器,客戶端是運行在瀏覽器中
- C/S結構,客戶端/服務器,客戶端是獨立的軟件
HTTP POST 簡易模型
go對HTTP的支持
在golang的net/http包中提供了HTTP客戶端和服務端的實現
Handle Func()可以設置函數的請求路徑
LIstenAndServer實現監聽服務
單控制器
發給處理器(Handler)
在Golang的net/http包下有ServeMutx實現了Front設計模式的Front窗口,ServeMux負責接收請求并把請求分發給處理器(Handler)
http.ServeMux實現了Handler接口
多控制器
在實際開發中大部分情況是不應該只有一個控制器的,不同的詩求應該交給不同的處理單元.
在Golang中支持兩種多處理方式
-
多個處理器(Handler)
-
多個處理函數(HandleFunc)
使用多處理器
- 使用http.Handle把不同的URL綁定到不同的處理器
- 在瀏覽器中輸入http://localhost:8090/myhandler或http://ocalhost:8090/myother可以訪問兩個處理器
方法.但是其他URI會出現404(資源未找到)頁面
package mainimport "net/http"type MyHandler struct {
}
type MyHandle struct {
}func (m *MyHandle) ServeHTTP(w http.ResponseWriter, r *http.Request) {w.Write([]byte("MyHandle--第二個"))
}func (m *MyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {w.Write([]byte("MyHandler"))
}func main() {h := MyHandler{}h2 := MyHandle{}server := http.Server{Addr: "localhost:8090"}http.Handle("/first", &h)http.Handle("/second", &h2)server.ListenAndServe()
}
使用多處理函數
func first(w http.ResponseWriter, r *http.Request) {fmt.Fprintln(w, "多函數first")
}
func second(w http.ResponseWriter, r *http.Request) {fmt.Fprintln(w, "多函數second")
}func main() {server := http.Server{Addr: "localhost:8090"}http.HandleFunc("/first", first)http.HandleFunc("/second", second)server.ListenAndServe()
}
獲取請求頭
package mainimport ("fmt""net/http"
)func param(w http.ResponseWriter, r *http.Request) {h := r.Header //mapfmt.Fprintln(w, h)for _, n := range h["Accept-Language"] {fmt.Fprintln(w, n)}
}func main() {server := http.Server{Addr: ":8090"}http.HandleFunc("/param", param)server.ListenAndServe()
}
獲取請求參數
可以一次性全部獲取也可以按照名稱獲取