HTTP Method / Header / Bodyの取得方法です。
package main
import (
"bytes"
"fmt"
"net/http"
)
func readBody(req *http.Request) string {
buf := new(bytes.Buffer)
buf.ReadFrom(req.Body)
return buf.String()
}
func rootHandler(w http.ResponseWriter, req *http.Request) {
// Method
fmt.Fprintf(w, "Moke server\nMethod=%s\n", req.Method)
// POST or PUTの時は本体を取ってみる。
if req.Method == "POST" || req.Method == "PUT" {
s := readBody(req)
fmt.Fprintf(w, "Body=\n%s", s)
}
// Headerは単なるMap
for k, v := range req.Header {
fmt.Fprintf(w, "Header[%s] = %s\n", k, v)
}
}
func main() {
http.HandleFunc("/", rootHandler)
http.ListenAndServe(":8080", nil)
}
リクエストを投げる時に使ったやつと同じですね。