快速入门

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
package main

import (
"encoding/json"
"fmt"
"github.com/kataras/iris"
"github.com/kataras/iris/middleware/logger"
"github.com/kataras/iris/middleware/recover"
"os"
)

func main() {
app := iris.New()
// 使用插件
app.Use(recover.New())
app.Use(logger.New())

// 配置1,读取字典
app.Configure(iris.WithConfiguration(iris.Configuration{
// 若是true,当人为中断程序时不会自动正常将服务器关闭,若是false,需要自定义处理
DisableInterruptHandler: false,
// 自动更正并将请求的路径重定向到已经注册的路径
// 如找不到/home/,将自动转为/home
EnablePathEscape: false,
TimeFormat: "Mon,02 Jan 2006 15:04:05 GMT",
Charset: "utf-8",
}))

// 配置2,读取文件
app.Configure(iris.WithConfiguration(iris.YAML("/user/.../iris.yaml")))

// 配置3,读取json文件
file, _ := os.Open("/User/.../config.json")
defer file.Close()
decoder := json.NewDecoder(file)
conf := Configuration{}
err := decoder.Decode(&conf)
if err != nil {
fmt.Println("error",err)
}
fmt.Println(conf.Port)

// Method: GET
// Resource: http://localhost:8080
app.Handle("GET", "/", func(ctx iris.Context) {
// 获取请求路径
path := ctx.Path()
// 获取请求参数
UserName := ctx.URLParam("username")
// 写入日志
app.Logger().Info(path, UserName)
// 返回HTML格式
ctx.HTML("<h1>Welcome" + UserName + "</h1>")
})

// same as app.Handle("GET", "/ping", [...])
// Method: GET
// Resource: http://localhost:8080/ping
app.Get("/ping", func(ctx iris.Context) {
// 返回text/plain数据
ctx.WriteString("pong")
})

// Method: Post
// Resource: http://localhost:8080/hello
app.Post("/hello", func(ctx iris.Context) {
// 获取post的form表单数据
UserName := ctx.PostValue("name")
app.Logger().Info(UserName)

// 获取post的json数据,并且解析成Person
// 同理,有ctx.ReadXML
var person Person
if err := ctx.ReadJSON(&person); err != nil {
panic(err.Error())
}
// 返回json数据格式
// iris.Map is just a type alias of the map[string]interface{} type.
ctx.JSON(iris.Map{"message": "Hello Iris!"})
})

// 不定路由
app.Get("/weather/{date}/{city}/{isLogin:bool}/{userid:uint64}", func(ctx iris.Context) {
// 获取不定路由参数
date := ctx.Params().Get("date")
// 获取bool值
isLogin, err := ctx.Params().GetBool("isLogin")
userid, err := ctx.Params().GetUint("userid")
if err == nil && isLogin {
app.Logger().Info("isLogin")
}
ctx.JSON(map[string]interface{}{
"requestCode": 200,
"userId": userid,
"date": date,
})
})

// 路由组, 类似于flask的bluePrint
userParty := app.Party("/users", func (ctx iris.Context) {
// 处理下一级请求
ctx.Next()
})
userParty.Get("/register", func(ctx iris.Context) {
ctx.WriteString("用户注册功能")
})

// 因为引入了ctx.Next,iris非常容易制作请求中间件
userRouter := app.Party("/admin", PathLogMiddleware)
userRouter.Get("/info", func(ctx iris.Context) {
ctx.WriteString("info")
})
userRouter.Get("/query", func(ctx iris.Context) {
ctx.WriteString("query")
ctx.Next() // 会调用userRouter.Done()
})
// Done:当二级路由的处理函数执行ctx.Next(),就会调用此函数
userRouter.Done(func(ctx iris.Context) {
ctx.Application().Logger().Infof("response to " + ctx.Path())
})

// 启动iris
app.Run(iris.Addr(":8080"))
}

type Configuration struct {
AppName string `json:"appname"`
Port string `json:"port"`
}

type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}

// 请求中间件,统一打印路径
func PathLogMiddleware(ctx iris.Context) {
path := ctx.Path()
// ctx.Application():类似于flask的Request.app:反向引用当前上下文对应的app
ctx.Application().Logger().Infof(path)
ctx.Next()
}

mvc包

mvc.Application

iris框架中的mvc包中提供了Application结构体定义,开发者可以通过注册自定义的controller来使用对应的API。

其中包含路由组router.Party,以此来注册layout.middleware以及相应的handlers