HTTP Requestのパラメータ

HTTP Requestのパラメータは以下の3種類がある。

  • パスパラメータ
  • クエリパラメータ
  • リクエストボディパラメータ

パスパラメータ(Path Parameter)

単一のパラメータ

基本的な書き方は次の通り

設計書

/item/{pathparameter}
/item/:pathparameter

呼び出し方法

http://example.com/item/1

複数のパラメータ

複数のパスパラメータを含むこともできる

設計書

/item/{group}/user/{level}
/item/:group/user/:level

呼び出し方法

http://example.com/item/1/user/10

Go Ginでの実装方法

r := gin.Default()
r.GET("/item/:pathparameter", func(c *gin.Context) {
    key := c.Param("pathparameter")
    fmt.Println(key)
})

クエリパラメータ(Query Parameter)

単一のパラメータ

設計書

/item{?queryparameter}

呼び出し方法

http://example.com/item?queryparameter=1

複数のパラメータ

設計書

/item{?group, level}

呼び出し方法

http://example.com/item?group=1&level=10

Go Ginでの実装方法

r := gin.Default()
r.GET("/item", func(c *gin.Context) {
    key := c.Query("queryparameter")
    fmt.Println(key)
})

リクエストボディパラメータ

設計書

ParametersRequestに書かれているもの。
json形式で表現されることが多い。

呼び出し方法

bodyに設定する必要がある。
ここでは curlでの呼び出しを例として挙げる。

curl -X POST -H "Content-Type: application/json" -d '{"Name":"bluemon", "Age":"35"}' 'http://example.com/item'

Go Ginでの実装方法

r := gin.Default()
r.POST("/item", func(c *gin.Context) {
    buf := make([]byte, 1024)
    n, _ := c.Request.Body.Read(buf)
    fmt.Println(string(buf[0:n]))
})