Bagian ini memperkenalkan bagaimana cara mendapatkan parameter permintaan GET, POST, dan lainnya dalam framework iris, termasuk membaca dan menulis cookie.
Parameter dalam Path
func main() {
app := iris.Default()
// Handler ini akan cocok dengan /user/john, tetapi tidak /user/ atau /user
app.Get("/user/{name}", func(ctx iris.Context) {
name := ctx.Params().Get("name")
ctx.Writef("Halo %s", name)
})
// Namun, handler ini akan cocok dengan /user/john/ dan /user/john/send
// Jika tidak ada router lain yang cocok dengan /user/john, itu akan dialihkan ke /user/john/
app.Get("/user/{name}/{action:path}", func(ctx iris.Context) {
name := ctx.Params().Get("name")
action := ctx.Params().Get("action")
message := name + " adalah " + action
ctx.WriteString(message)
})
// Untuk setiap permintaan yang cocok, konteks akan menjaga definisi router
app.Post("/user/{name:string}/{action:path}", func(ctx iris.Context) {
ctx.GetCurrentRoute().Tmpl().Src == "/user/{name:string}/{action:path}" // true
})
app.Listen(":8080")
}
Tersedia parameter bawaan:
Tipe Parameter | Tipe Go | Validasi | Fungsi Bantu Akses |
---|---|---|---|
:string |
string | Semua konten (segmen path tunggal) | Params().Get |
:uuid |
string | uuidv4 atau v1 (segmen path tunggal) | Params().Get |
:int |
int | -9223372036854775808 hingga 9223372036854775807 (x64) atau -2147483648 hingga 2147483647 (x32), tergantung pada arsitektur host | Params().GetInt |
:int8 |
int8 | -128 hingga 127 | Params().GetInt8 |
:int16 |
int16 | -32768 hingga 32767 | Params().GetInt16 |
:int32 |
int32 | -2147483648 hingga 2147483647 | Params().GetInt32 |
:int64 |
int64 | -9223372036854775808 hingga 9223372036854775807 | Params().GetInt64 |
:uint |
uint | 0 hingga 18446744073709551615 (x64) atau 0 hingga 4294967295 (x32), tergantung pada arsitektur host | Params().GetUint |
:uint8 |
uint8 | 0 hingga 255 | Params().GetUint8 |
:uint16 |
uint16 | 0 hingga 65535 | Params().GetUint16 |
:uint32 |
uint32 | 0 hingga 4294967295 | Params().GetUint32 |
:uint64 |
uint64 | 0 hingga 18446744073709551615 | Params().GetUint64 |
:bool |
bool | "1" atau "t" atau "T" atau "TRUE" atau "true" atau "True" atau "0" atau "f" atau "F" atau "FALSE" atau "false" atau "False" | Params().GetBool |
:alphabetical |
string | Huruf kecil atau huruf besar | Params().Get |
:file |
string | Huruf kecil atau huruf besar, angka, garis bawah (_), tanda hubung (-), titik (.), tidak boleh mengandung spasi atau karakter khusus nama file lainnya yang tidak valid | Params().Get |
:path |
string | Semua konten, dapat dipisahkan dengan garis miring (segmen path), tetapi harus menjadi bagian terakhir dari path router | Params().Get |
:mail |
string | Alamat email, domain tidak divalidasi | Params().Get |
:email |
string | Alamat email, domain divalidasi | Params().Get |
:date |
string | Format yyyy/mm/dd, misalnya /blog/{param:date} cocok dengan /blog/2022/04/21 | Params().GetTime dan Params().SimpleDate |
:weekday |
uint (0-6) or string | String harus menjadi konstanta time.Weekday ("sunday" hingga "monday" atau "Sunday" hingga "Monday") format, misalnya /schedule/{param:weekday} cocok dengan /schedule/monday | Params().GetWeekday |
Mendapatkan Parameter Query
func main() {
app := iris.Default()
// Parsing parameter string query menggunakan objek permintaan tingkat rendah yang sudah ada.
// Permintaan URL cocok: /welcome?firstname=Jane&lastname=Doe
app.Get("/welcome", func(ctx iris.Context) {
firstname := ctx.URLParamDefault("firstname", "Tamu")
lastname := ctx.URLParam("lastname") // Pintasan untuk ctx.Request().URL.Query().Get("lastname")
ctx.Writef("Halo %s %s", firstname, lastname)
})
app.Listen(":8080")
}
Mendapatkan Parameter Form
func main() {
app := iris.Default()
app.Post("/form_post", func(ctx iris.Context) {
message := ctx.PostValue("message")
nick := ctx.PostValueDefault("nick", "Anonim")
ctx.JSON(iris.Map{
"status": "Dipublikasikan",
"message": message,
"nick": nick,
})
})
app.Listen(":8080")
}
Contoh Gabungan Parameter Query + Form
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
Mengambil Parameter Query dalam Permintaan 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]
Membaca/Menulis Cookie
import "github.com/kataras/iris/v12"
func main() {
app := iris.Default()
app.Get("/cookie", func(ctx iris.Context) {
// Baca cookie
value := ctx.GetCookie("my_cookie")
if value == "" {
value = "BelumDiatur"
// Buat cookie
ctx.SetCookieKV("my_cookie", value)
// Atau: ctx.SetCookie(&http.Cookie{...})
// Buat cookie
ctx.SetCookie("", "test", 3600, "/", "localhost", false, true)
}
ctx.Writef("Nilai Cookie: %s \n", value)
})
app.Listen(":8080")
}