1、设置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!")) }
2、获取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 }