Эта глава представляет, как получить GET, POST и другие параметры запроса в iris framework, включая чтение и запись cookies.
Параметры в пути
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 | Любое содержимое (один сегмент пути) | Params().Get |
:uuid |
string | uuidv4 или v1 (один сегмент пути) | 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", "Гость")
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", "Аноним")
ctx.JSON(iris.Map{
"status": "Опубликовано",
"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?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) {
// Чтение cookie
value := ctx.GetCookie("my_cookie")
if value == "" {
value = "NotSet"
// Создание cookie
ctx.SetCookieKV("my_cookie", value)
// Вариант: ctx.SetCookie(&http.Cookie{...})
// Создание cookie
ctx.SetCookie("", "test", 3600, "/", "localhost", false, true)
}
ctx.Writef("Значение cookie: %s \n", value)
})
app.Listen(":8080")
}