この章では、irisフレームワークでGET、POSTなどのリクエストパラメータを取得する方法と、クッキーの読み書きについて紹介します。
パス内のパラメータ
func main() {
app := iris.Default()
// このハンドラは/user/johnにはマッチしますが、/user/や/userにはマッチしません
app.Get("/user/{name}", func(ctx iris.Context) {
name := ctx.Params().Get("name")
ctx.Writef("こんにちは %s", name)
})
// しかし、このハンドラは/user/john/や/user/john/sendにもマッチします
// /user/johnに他のルータがマッチしない場合、/user/john/にリダイレクトされます
app.Get("/user/{name}/{action:path}", func(ctx iris.Context) {
name := ctx.Params().Get("name")
action := ctx.Params().Get("action")
message := name + "は" + action
ctx.WriteString(message)
})
// 一致するリクエストごとに、コンテキストはルーターの定義を保持します
app.Post("/user/{name:string}/{action:path}", func(ctx iris.Context) {
ctx.GetCurrentRoute().Tmpl().Src == "/user/{name:string}/{action:path}" // true
})
app.Listen(":8080")
}
組み込みの利用可能なパラメータタイプ:
パラメータタイプ | Goの型 | 検証 | アクセス補助関数 |
---|---|---|---|
:string |
string | 任意の内容(1つのパスセグメント) | Params().Get |
:uuid |
string | uuidv4またはv1(1つのパスセグメント) | Params().Get |
:int |
int | -9223372036854775808から9223372036854775807(x64)または-2147483648から2147483647(x32)、ホストアーキテクチャに応じて | Params().GetInt |
:int8 |
int8 | -128から127 | Params().GetInt8 |
:int16 |
int16 | -32768から32767 | Params().GetInt16 |
:int32 |
int32 | -2147483648から2147483647 | Params().GetInt32 |
:int64 |
int64 | -9223372036854775808から9223372036854775807 | Params().GetInt64 |
:uint |
uint | 0から18446744073709551615(x64)または0から4294967295(x32)、ホストアーキテクチャに応じて | Params().GetUint |
:uint8 |
uint8 | 0から255 | Params().GetUint8 |
:uint16 |
uint16 | 0から65535 | Params().GetUint16 |
:uint32 |
uint32 | 0から4294967295 | Params().GetUint32 |
:uint64 |
uint64 | 0から18446744073709551615 | Params().GetUint64 |
:bool |
bool | "1"または"t"または"T"または"TRUE"または"true"または"True"または"0"または"f"または"F"または"FALSE"または"false"または"False" | Params().GetBool |
:alphabetical |
string | 小文字または大文字のアルファベット | Params().Get |
:file |
string | 小文字または大文字のアルファベット、数字、アンダースコア(_)、ハイフン(-)、ピリオド(.)を含む、スペースや他のバリッドでないファイル名特殊文字を含めることはできません | Params().Get |
:path |
string | 任意の内容、スラッシュで区切ることができます(パスセグメント)、ただし、ルートパスの最後の部分である必要があります | Params().Get |
:mail |
string | ドメインは検証されませんので、メールアドレス | Params().Get |
:email |
string | ドメインが検証されるメールアドレス | Params().Get |
:date |
string | 形式はyyyy/mm/dd、たとえば/blog/{param:date}は/blog/2022/04/21にマッチします | Params().GetTime およびParams().SimpleDate |
:weekday |
uint(0-6)またはstring | 文字列はtime.Weekday定数("Sunday"から"Monday"または"Sunday"から"Monday")である必要があります、たとえば/schedule/{param:weekday}は/schedule/mondayにマッチします | Params().GetWeekday |
クエリパラメータの取得
func main() {
app := iris.Default()
// 既存の低レベルリクエストオブジェクトを使用してクエリ文字列パラメータを解析します。
// リクエストURL一致: /welcome?firstname=Jane&lastname=Doe
app.Get("/welcome", func(ctx iris.Context) {
firstname := ctx.URLParamDefault("firstname", "Guest")
lastname := ctx.URLParam("lastname") // ctx.Request().URL.Query().Get("lastname")のショートカット
ctx.Writef("こんにちは %s %s", firstname, lastname)
})
app.Listen(":8080")
}
フォームパラメータの取得
func main() {
app := iris.Default()
app.Post("/form_post", func(ctx iris.Context) {
message := ctx.PostValue("message")
nick := ctx.PostValueDefault("nick", "Anonymous")
ctx.JSON(iris.Map{
"status": "Published",
"message": message,
"nick": nick,
})
})
app.Listen(":8080")
}
クエリとフォームパラメーターの組み合わせ例
POST /post?id=1234&page=1 HTTP/1.1
Content-Type: application/x-www-form-urlencoded
name=kataras&message=this_is_great
func main() {
app := iris.Default()
app.Post("/post", func(ctx iris.Context) {
id, err := ctx.URLParamInt("id", 0)
if err != nil {
ctx.StopWithError(iris.StatusBadRequest, err)
return
}
page := ctx.URLParamIntDefault("page", 0)
name := ctx.PostValue("name")
message := ctx.PostValue("message")
ctx.Writef("id: %d; page: %d; name: %s; message: %s", id, page, name, message)
})
app.Listen(":8080")
}
id: 1234; page: 1; name: kataras; message: this_is_great
POSTリクエストでのクエリパラメータの取得
POST /post?id=a&id=b&id=c&name=john&name=doe&name=kataras
Content-Type: application/x-www-form-urlencoded
func main() {
app := iris.Default()
app.Post("/post", func(ctx iris.Context) {
ids := ctx.URLParamSlice("id")
names, err := ctx.PostValues("name")
if err != nil {
ctx.StopWithError(iris.StatusBadRequest, err)
return
}
ctx.Writef("ids: %v; names: %v", ids, names)
})
app.Listen(":8080")
}
ids: [a b c], names: [john doe kataras]
クッキーの読み込み/書き込み
import "github.com/kataras/iris/v12"
func main() {
app := iris.Default()
app.Get("/cookie", func(ctx iris.Context) {
// クッキーの読み込み
value := ctx.GetCookie("my_cookie")
if value == "" {
value = "NotSet"
// クッキーの作成
ctx.SetCookieKV("my_cookie", value)
// 代替: ctx.SetCookie(&http.Cookie{...})
// クッキーの作成
ctx.SetCookie("", "test", 3600, "/", "localhost", false, true)
}
ctx.Writef("クッキーの値: %s \n", value)
})
app.Listen(":8080")
}