技術向上

プログラミングの学び、気になるテクノロジーやビジネストレンドを発信

http.Requestからformの値を取得する【Go】

http.Requestからformの値を取得するには、
http.Requestのメソッド、ParseForm()事前に実行する必要があります。
その上で、formの値が格納されているhttp.Requestのフィールド(url.Values型)にアクセスします。

formの値が格納されるフィールドには、FormとPostFormがあります。

Formは、formからPOSTまたはPUTされた値とURLのクエリパラメータから取得することができます。
PostFormが取得するのはformからPOST、PUT、またはPATCHされた値のみです。

今回はFormを使ってtemplateに値を渡し、サーバーを起動する例を取り上げます。

main.goは次のようにします。

type hotdog int    // 型は何でもよい

var tpl *template.Template

func (h hotdog) ServeHTTP(w http.ResponseWriter, r *http.Request) {    // hotdogがHandler型とみなされるように、ServeHTTP()メソッドを実装する
    err := r.ParseForm()    // http.Requestのフィールド、Formを取得するためには、事前にParseForm()の実行が必要
    if err != nil {
        log.Fatal(err)
    }
    tpl.ExecuteTemplate(w, "tpl.gohtml", r.Form)    // Formをtemplateに渡す
}

func init() {
    tpl = template.Must(template.ParseGlob("templates/*"))    // tpl.gohtmlがtemplates以下にある想定
}

func main() {
    var h hotdog
    http.ListenAndServe(":8080", h)    // hotdog型のhをHandlerとして、localhost:8080にサーブ
}


これでtpl.gohtml側にて、「{{.}}」でFormの値を受け取ることができます。

http.RequestにはFormの他にもMethodやURLなどのフィールドが存在します。
次のように取得、templateに渡すことも可能です。

func (h hotdog) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    err := req.ParseForm()
    if err != nil {
        log.Fatal(err)
    }

    data := struct {    // それぞれにあった型のフィールドを用意して、値を定義する
        Method        string
        URL           *url.URL
        Submissions   map[string][]string
        Header        http.Header
        Host          string
        ContentLength int64
    }{
        req.Method,
        req.URL,
        req.Form,
        req.Header,
        req.Host,
        req.ContentLength,
    }
    tpl.ExecuteTemplate(w, "tpl.gohtml", data)
}