Questo capitolo introduce come ottenere i parametri della richiesta GET, POST e altri nel framework iris, incluso la lettura e scrittura dei cookie.
Parametri nel percorso
func main() {
app := iris.Default()
// Questo gestore corrisponderà a /user/john, ma non a /user/ o /user
app.Get("/user/{name}", func(ctx iris.Context) {
name := ctx.Params().Get("name")
ctx.Writef("Ciao %s", name)
})
// Tuttavia, questo gestore corrisponderà a /user/john/ e /user/john/send
// Se nessun altro percorso corrisponde a /user/john, verrà reindirizzato a /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)
})
// Per ogni richiesta corrispondente, il contesto conserverà la definizione del percorso
app.Post("/user/{name:string}/{action:path}", func(ctx iris.Context) {
ctx.GetCurrentRoute().Tmpl().Src == "/user/{name:string}/{action:path}" // true
})
app.Listen(":8080")
}
Tipi di parametro incorporati disponibili:
Tipo di parametro | Tipo Go | Validazione | Funzione di accesso ausiliare |
---|---|---|---|
:string |
stringa | Qualsiasi contenuto (singolo segmento del percorso) | Params().Get |
:uuid |
stringa | uuidv4 o v1 (singolo segmento del percorso) | Params().Get |
:int |
int | -9223372036854775808 to 9223372036854775807 (x64) o -2147483648 a 2147483647 (x32), a seconda dell'architettura host | Params().GetInt |
:int8 |
int8 | -128 a 127 | Params().GetInt8 |
:int16 |
int16 | -32768 a 32767 | Params().GetInt16 |
:int32 |
int32 | -2147483648 a 2147483647 | Params().GetInt32 |
:int64 |
int64 | -9223372036854775808 a 9223372036854775807 | Params().GetInt64 |
:uint |
uint | 0 a 18446744073709551615 (x64) o 0 a 4294967295 (x32), a seconda dell'architettura host | Params().GetUint |
:uint8 |
uint8 | 0 a 255 | Params().GetUint8 |
:uint16 |
uint16 | 0 a 65535 | Params().GetUint16 |
:uint32 |
uint32 | 0 a 4294967295 | Params().GetUint32 |
:uint64 |
uint64 | 0 a 18446744073709551615 | Params().GetUint64 |
:bool |
bool | "1" o "t" o "T" o "TRUE" o "true" o "True" o "0" o "f" o "F" o "FALSE" o "false" o "False" | Params().GetBool |
:alfabetico |
stringa | Lettere minuscole o maiuscole | Params().Get |
:file |
stringa | Lettere minuscole o maiuscole, numeri, underscore (_), trattino (-), punto (.), non può contenere spazi o altri caratteri speciali non validi per i nomi file | Params().Get |
:percorso |
stringa | Qualsiasi contenuto, può essere separato da barre (segmenti del percorso), ma dovrebbe essere l'ultima parte del percorso del percorso | Params().Get |
:mail |
stringa | Indirizzo email, dominio non convalidato | Params().Get |
:email |
stringa | Indirizzo email, dominio convalidato | Params().Get |
:data |
stringa | Formato yyyy/mm/dd, ad esempio /blog/{param:date} corrisponde a /blog/2022/04/21 | Params().GetTime e Params().SimpleDate |
:giornosettimana |
uint (0-6) o stringa | La stringa deve essere una costante time.Weekday ("domenica" a "lunedì" o "Sunday" a "Monday"), ad esempio /schedule/{param:weekday} corrisponde a /schedule/lunedì | Params().GetWeekday |
func main() {
app := iris.Default()
// Analizza i parametri della stringa di query utilizzando l'oggetto richiesta a basso livello esistente.
// Corrispondenza dell'URL della richiesta: /welcome?firstname=Jane&lastname=Doe
app.Get("/welcome", func(ctx iris.Context) {
firstname := ctx.URLParamDefault("firstname", "Ospite")
lastname := ctx.URLParam("lastname") // Scorciatoia per ctx.Request().URL.Query().Get("lastname")
ctx.Writef("Ciao %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", "Anonimo")
ctx.JSON(iris.Map{
"status": "Pubblicato",
"messaggio": 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; messaggio: %s", id, page, name, message)
})
app.Listen(":8080")
}
id: 1234; page: 1; name: kataras; messaggio: 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; nomi: %v", ids, names)
})
app.Listen(":8080")
}
import "github.com/kataras/iris/v12"
func main() {
app := iris.Default()
app.Get("/cookie", func(ctx iris.Context) {
// Leggi cookie
value := ctx.GetCookie("my_cookie")
if value == "" {
value = "NonImpostato"
// Crea cookie
ctx.SetCookieKV("my_cookie", value)
// In alternativa: ctx.SetCookie(&http.Cookie{...})
// Crea cookie
ctx.SetCookie("", "test", 3600, "/", "localhost", false, true)
}
ctx.Writef("Valore del cookie: %s \n", value)
})
app.Listen(":8080")
}