golang http编程
1、http请求包,报文格式
请求行:请求方法,,请求文件URL,协议版本
请求头:语法格式:key:value
空行:\r\n
请求包体:请求方法对应的数据内容。GET方法没有内容!!
2、http响应包,报文格式
3、设置http头和状态码
golang中设置http头用 w.Header().Set() ,设置状态码用 w.WriteHeader() , 设置body用 w.Write() 。但他们的调用顺序是有要求的。正确的调用顺序如下
func HandleHello(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-name","john")
w.WriteHeader(http.StatusOK)
w.Write([]byte("hello world!"))
}
4、获取http:127.0.0.1:8080/provisions/{id}模式中id的方法
import (
"fmt"
"github.com/gorilla/mux"
"net/http"
)
func main() {
r := mux.NewRouter()
r.HandleFunc("/provisions/{id}", Provisions)
http.ListenAndServe(":8080", r)
}
func Provisions(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, ok := vars["id"]
if !ok {
fmt.Println("id is missing in parameters")
}
fmt.Println(`id := `, id)
//call http://localhost:8080/provisions/someId in your browser
//Output : id := someId
}


浙公网安备 33010602011771号