mirror of
https://github.com/kataras/iris.git
synced 2025-12-19 19:07:06 +00:00
Add More Examples & Categorized in Folders & TOC
Former-commit-id: ce4d711a75a4ba08ffab075e6baa88724725885b
This commit is contained in:
41
_examples/examples/advanced/httptest/main.go
Normal file
41
_examples/examples/advanced/httptest/main.go
Normal file
@@ -0,0 +1,41 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
|
||||
"gopkg.in/kataras/iris.v6/adaptors/sessions"
|
||||
)
|
||||
|
||||
func newApp() *iris.Framework {
|
||||
app := iris.New()
|
||||
app.Adapt(httprouter.New())
|
||||
app.Adapt(sessions.New(sessions.Config{Cookie: "mysessionid"}))
|
||||
|
||||
app.Get("/hello", func(ctx *iris.Context) {
|
||||
sess := ctx.Session()
|
||||
if !sess.HasFlash() /* or sess.GetFlash("name") == "", same thing here */ {
|
||||
ctx.HTML(iris.StatusUnauthorized, "<h1> Unauthorized Page! </h1>")
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(iris.StatusOK, iris.Map{
|
||||
"Message": "Hello",
|
||||
"From": sess.GetFlash("name"),
|
||||
})
|
||||
})
|
||||
|
||||
app.Post("/login", func(ctx *iris.Context) {
|
||||
sess := ctx.Session()
|
||||
if !sess.HasFlash() {
|
||||
sess.SetFlash("name", ctx.FormValue("name"))
|
||||
}
|
||||
// let's no redirect, just set the flash message, nothing more.
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
|
||||
func main() {
|
||||
app := newApp()
|
||||
app.Listen(":8080")
|
||||
}
|
||||
32
_examples/examples/advanced/httptest/main_test.go
Normal file
32
_examples/examples/advanced/httptest/main_test.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"gopkg.in/kataras/iris.v6/httptest"
|
||||
)
|
||||
|
||||
// $ cd _example
|
||||
// $ go test -v
|
||||
func TestNewApp(t *testing.T) {
|
||||
app := newApp()
|
||||
e := httptest.New(app, t)
|
||||
|
||||
// test nauthorized
|
||||
e.GET("/hello").Expect().Status(401).Body().Equal("<h1> Unauthorized Page! </h1>")
|
||||
// test our login flash message
|
||||
name := "myname"
|
||||
e.POST("/login").WithFormField("name", name).Expect().Status(200)
|
||||
// test the /hello again with the flash (a message which deletes itself after it has been shown to the user)
|
||||
// setted on /login previously.
|
||||
expectedResponse := map[string]interface{}{
|
||||
"Message": "Hello",
|
||||
"From": name,
|
||||
}
|
||||
e.GET("/hello").Expect().Status(200).JSON().Equal(expectedResponse)
|
||||
// test /hello nauthorized again, it should be return 401 now (flash should be removed)
|
||||
e.GET("/hello").Expect().Status(401).Body().Equal("<h1> Unauthorized Page! </h1>")
|
||||
}
|
||||
|
||||
// for advanced test examples navigate there:
|
||||
// https://github.com/gavv/httpexpect/blob/master/_examples/iris_test.go
|
||||
Reference in New Issue
Block a user