Skip to content

gofrのcontextを知る

Posted on:2023年12月22日

link

すべての QueryParams を取得する

`http://localhost:8000/user?name=oidon&isStudent=true この API の場合

ctx.Params()

↑ で、

{
  "name": "oidon",
  "isStudent": "true"
}

が取得できる

If the same key has multiple values then the value in c.Params will be comma-separated.

http://localhost:8000/user?name=oidon&isStudent=true&name=umaidashi とすると

{
  "name": "oidon,umaidashi",
  "isStudent": "true"
}

とカンマ区切りにしてくれる

任意の QueryParam を取得する

`http://localhost:8000/user?name=oidon&isStudent=true この API の場合

ctx.Param("name")

で、

"oidon"

が取れる

パスから値を取得する

app.GET("/user/{id}", func(ctx *gofr.Context) (interface{}, error) {
    ...
})

api のエンドポイントに {} でパラメータを定義(今回はid

ctx.PathParam("id")

idが取得できる

リクエストボディの取得

  1. ボディの型を定義
type user struct {
    Name string `json:name`
    Age  int    `json:age`
}
  1. BindStrict
var u user
if err := ctx.BindStrict(&u); err != nil {
    return nil, err
}

アドレスを渡す必要がある(&u)の部分

u.Name, u.Age というように使える

ヘッダー

c.Header(<header_name>) で取れる

c.Header("Content-Type")

だと application/json