LoginSignup
10
5

More than 3 years have passed since last update.

Goで受け取ったhttp.Requestパラメータを全て取得する

Posted at

パラメータ名を指定して取得する場合

http.RequestからGET/POSTされたパラメータを取得する際に、キー名を指定する場合はFormValue()を用いることができます。

main.go
package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/sample1", Sample1)
    http.ListenAndServe(":8080", nil)
}

// Sample1 ハンドラ
func Sample1(w http.ResponseWriter, r *http.Request) {
    fmt.Println("hoge", r.FormValue("hoge"))
    fmt.Println("foo", r.FormValue("foo"))
}

下記のようにリクエストを送信するとデータが取得できていることが分かります。

$ curl --location --request GET 'http://localhost:8080/?hoge=aaa&foo=bbb'
標準出力
hoge aaa
foo bbb

パラメータを全て取得する場合

ミドルウェア等を作成する場合、キー名によって処理を変えたいこともあります。
どのようなパラメータがリクエストされてくるのかが分からないため、事前にパラメータを指定できません。
そのため、処理を行おうとすると全てのパラメータを取得する必要があります。

その場合はParseForm()を行うことでデータをFormから取得できるようになります。

main.go
// 前略

// Sample2 ハンドラ
func Sample2(w http.ResponseWriter, r *http.Request) {
    if err := r.ParseForm(); err != nil {
        fmt.Println("errorだよ")
    }

    for k, v := range r.Form {
        fmt.Printf("%v : %v\n", k, v)
    }
}
標準出力
hoge : [aaa]
foo : [bbb]

なお、画像等を扱う際はmultipart/form-dataを扱うと思いますが、その際もParseForm()を行うことでMultipartFormから取得が可能です。

main.go
// 前略

// Sample3 ハンドラ
func Sample3(w http.ResponseWriter, r *http.Request) {
    if err := r.ParseMultipartForm(32 << 20); err != nil {
        fmt.Println("errorだよ")
    }

    mf := r.MultipartForm

    // 通常のリクエスト
    for k, v := range mf.Value {
        fmt.Printf("%v : %v", k, v)
    }

    // ファイル等バイナリのリクエスト
    for k, v := range mf.Value {
        fmt.Printf("%v : %v", k, v)
    }
}
POSTサンプル
curl --location --request POST 'http://localhost:8080/sample3' \
--header 'Content-Type: multipart/form-data; boundary=--------------------------897380512801959426741215' \
--form 'image_file=@/path/to/file/sample_image.png' \
--form 'hoge=aaa' \
--form 'foo=bbb'
標準出力
hoge : [aaa]
foo : [bbb]
image_file : 0 : sample_image.png
image_file : 0 : map[Content-Disposition:[form-data; name="image_file"; filename="sample_image.png"] Content-Type:[image/png]]
image_file : 0 : 19487

サンプルコード

コードは下記にも置いておきます。
https://github.com/ayatothos/go-samples/tree/master/form_params

10
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
5