我的第一個Go web程序 紀念一下
阿新 • • 發佈:2018-03-22
brush 選擇 pan fmt resp main nbsp gpo pac
參考Go web編程,很簡單的程序:
大致的步驟:
- 綁定ip和端口
- 綁定對應的處理器或者處理器函數,有下面兩種選擇,選擇一種即可監聽ip及端口
- 處理器:
- 定義一個struct結構體
- 然後讓這個結構體實現ServeHTTP的接口
- 創建一個該結構的實例
- 將該實例的地址(指針)作為參數傳遞給Handle
- 處理器函數
- 定義一個函數
- 該函數必須和ServeHTTP一樣的函數簽名
- 函數名直接作為參數傳遞給HandleFunc
- 處理器:
- 訪問綁定的ip加port
使用處理器形式:
package main import ( "fmt" "net/http" ) type Home struct{} type About struct{} func (h *Home) ServeHTTP(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "this is home") } func (a *About) ServeHTTP(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "this is about") } func main() { server := http.Server{ Addr: "127.0.0.1:8080", } home := &Home{} about := &About{} http.Handle("/home", home) http.Handle("/about", about) server.ListenAndServe() }
使用處理器函數形式:
package main import ( "fmt" "net/http" ) func home(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "this is home2") } func about(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "this is about2") } func main() { server := http.Server{ Addr: "127.0.0.1:8080", } http.HandleFunc("/home", home) http.HandleFunc("/about", about) server.ListenAndServe() }
我的第一個Go web程序 紀念一下