如何使用Iris框架的基本请求
解决问题:使用iris框架接收来自浏览器的各种基本请求
前言
要是还不会启动iris框架的,可以看我的上一篇BlogGo web系列 iris框架的搭建。今天就讲解如何使用iris框架接收来自浏览器的各种基本请求,常见的请求有Get、Post、Put…
Get请求
函数原型
func (api *APIBuilder) Get(relativePath string, handlers ...context.Handler) *Route {
return api.Handle(http.MethodGet, relativePath, handlers...)
}
具体使用
//获取来自浏览器的Get请求 ,path为 '\'
app.Get("/", func(ctx iris.Context) {
//获取path
path := ctx.Path()
//访问成功,先前端反馈"suc"
ctx.WriteString("suc")
//使用log日志输出路径
app.Logger().Info(path)
})
启动web框架,使用postman向浏览器发送GET请求
终端中的log输出
Post请求
函数原型
func (api *APIBuilder) Post(relativePath string, handlers ...context.Handler) *Route {
return api.Handle(http.MethodPost, relativePath, handlers...)
}
具体使用
//url: http://localhost:9999/post?name=smartzou&pwd=123
app.Post("/post", func(ctx iris.Context) {
//处理POST请求,请求url /post
path := ctx.Path()
app.Logger().Info(path)
//获取post请求值
username := ctx.PostValue("username")
pwd := ctx.PostValue("pwd")
//在终端中输出
app.Logger().Info(username, " ", pwd)
//输出<h1>标签
ctx.HTML("<h1>" + username + "," + pwd + "</h1>")
})
处理前端发送的JSON
//这里的person是一个结构体对象,结构与json的对象相同
//定义如下
type Person struct {
username string `json:"username"`
pwd int `json:"pwd"`
}
//解析json
err := ctx.ReadJSON(&person); if err != nil {
panic(err.Error())
}
Put请求
函数原型
func (api *APIBuilder) Put(relativePath string, handlers ...context.Handler) *Route {
return api.Handle(http.MethodPut, relativePath, handlers...)
}
具体使用
// url: http://localhost:9999/put
app.Put("/put", func(ctx iris.Context) {
path:=ctx.Path()
//在终端中输出log
app.Logger().Info(path)
//返回页面
ctx.Writef("methdo:%s path:%s",ctx.Method(),ctx.Path())
})
Delete请求
函数原型
func (api *APIBuilder) Delete(relativePath string, handlers ...context.Handler) *Route {
return api.Handle(http.MethodDelete, relativePath, handlers...)
}
具体实现
// url: http://localhost:9999/delete
app.Delete("/delete", func(ctx iris.Context) {
path:=ctx.Path()
//在终端中输出log
app.Logger().Info(path)
//返回页面
ctx.Writef("methdo:%s path:%s",ctx.Method(),ctx.Path())
})
app.Handle()
其实上面介绍的4种请求和其他的请求都可以使用一种函数来定义
函数原型
func (api *APIBuilder) Handle(method string, relativePath string, handlers ...context.Handler) *Route {}
具体实现
//url http://localhost:9999/info/znzasf
//第一个参数为请求格式 第二个参数为具体路径,最后一个是ctx。。。
//这里需要注意的是{city},这个是动态的
app.Handle("GET","/info/{city}", func(context iris.Context) {
path:=context.Path()
//获取City的值
city:=context.Params().Get("city")
app.Logger().Info(path)
//返回值为city
context.WriteString(city)
})
Postman结果
log输出
总结
今天将了最常用的几种基本请求,明天更新路由组…Never give up!!!
2020.6.19