Iris
iris
前言
Iris:最快的Go语言Web框架,完备MVC支持
Iris是一个快速,简单但功能齐全的和非常有效的web框架,提供了一个优美的表现能力和容易使用你的下一个网站和API的基础
Gin:Go语言编写的web框架,以更好的性能实现类似Martini框架的API
Gin是一个golang的微框架,封装比较优雅,API友好,源码注释比较明确。具有快速灵活,容错方便等特点
Beego:开源的高性能Go语言框架
beego是一个快速开发Go应用的http框架,go语言方面技术大牛。beego可以用来快速开发API、web、后端服务等各种应用,是一个RESTFul等框架,主要设计令该来源于tornado、sinatra、flask这三个框架,但是结合了Go本身等一些特性(interface、strict)而设计的框架
Iris简介
Iris是一款Go语言中朋来开发web应用的框架,该框架支持编写一次并在任何地方以最小的机器功率运行,如android、ios、Linux和Windows等。该框架只需要一个可执行的服务就可以在平台上运行。
Iris框架以简单而强大的api而被开发者所熟悉。iris除了为开发者提供非常简单的访问方式外,还同样支持MVC。另外,用iris构建为服务也很容易。
在iris框架的官方网站上,被称为速度最快的Go后端开发框架。
github:https://github.com/kataras/iris
官方文档:https://www.iris-go.com/docs/#/
安装iris
go get github.com/kataras/iris/v12@master
package main
import "github.com/kataras/iris/v12"
func main() {
app := iris.New()
//iris.Compression 是iris内部对IO数据进行压缩的模块,可以提高数据传输速度
app.Use(iris.Compression)
//localhost:8080/hello
app.Get("/hello", hello)
app.Listen(":8080")
}
func hello(ctx iris.Context) {
ctx.HTML("hello <strong>%s</strong>!", "world")
}
RestFul API
API name | 非Restful | restful |
---|---|---|
获取dog | /dogs.query/ | GET:/dogs/ |
插入dog | /dogs/add | POST:/dogs |
更新dog | /dogs/update/ | PUT:/dogs/ |
删除dog | /dogs/delete/ | DELETE:/dogs/ |
//RestFul 接口规范
app.Post("/user", func(context *context.Context) {})
app.Delete("/user", func(context *context.Context) {})
app.Put("/user", func(context *context.Context) {})
app.Get("/user", func(context *context.Context) {})
//常规规范
app.Post("/user/add/teacher")
app.Post("/user/updata")
app.Post("/user/delete")
app.Post("/users")
请求处理与响应
package main
import (
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/context"
)
func main() {
app := iris.New()
//iris.Compression 是iris内部对IO数据进行压缩的模块,可以提高数据传输速度
app.Use(iris.Compression)
//localhost:8080/hello
app.Get("/hello", func(ctx iris.Context) {
ctx.HTML("hello <strong>%s</strong>!", "world")
})
app.Get("/user", func(context *context.Context) {
path := context.Path()
app.Logger().Info(path)
context.WriteString("请求路径:" + path)
//获取请求中的参数
userid := context.URLParam("id")
//业务逻辑
app.Logger().Info(userid)
context.WriteString(userid)
})
//http://localhost:8080/welcome?userid=1&username=yama
app.Get("/welcome", func(ctx iris.Context) {
path := ctx.Path()
app.Logger().Info(path)
ctx.WriteString("请求路径:" + path)
userid := ctx.URLParam("userid")
useriname := ctx.URLParam("username")
app.Logger().Info(userid + "---" + useriname)
ctx.WriteString(userid + "---" + useriname)
})
//路径传参
//http://localhost:8090/path/1/yama
app.Get("/path/{userid:int}/{username:string}", func(context *context.Context) {
userid := context.Params().Get("userid")
username := context.Params().Get("username")
app.Logger().Info(userid + "---" + username)
context.WriteString(userid + "---" + username)
})
//处理表单
app.Post("/user/login", func(context *context.Context) {
//获取表单的参数
username := context.PostValue("username")
password := context.PostValue("password")
//业务逻辑
app.Logger().Info(username + "----" + password)
context.WriteString(username + "----" + password)
})
//json
app.Post("/user/json", func(context *context.Context) {
//获取json
var user = struct {
Username string `json:"username"`
Password string `json:"password"`
}{}
err := context.ReadJSON(&user)
if err != nil {
panic(err)
}
app.Logger().Info(user)
//返回json
context.JSON(iris.Map{"msg": user.Username, "doce": 200})
})
app.Listen(":8090")
}
路由器
使用的app.Get()等函数来获取前端发送的请求,但当路由多了管理起来就比较麻烦,有一种相对起来比较高效的方法,路由分组
package main
import (
"fmt"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/context"
)
func main() {
app := iris.New()
//iris.Compression 是iris内部对IO数据进行压缩的模块,可以提高数据传输速度
app.Use(iris.Compression)
//localhost:8080/hello
userParty := app.Party("/user", func(context *context.Context) {
//统一处理
fmt.Println("userParty->")
context.Next()
})
userParty.Get("/login", func(c *context.Context) {})
userParty.Get("/logout", func(c *context.Context) {})
userParty.Get("/register", func(c *context.Context) {})
userParty.Get("/...", func(c *context.Context) {})
userParty.Get("/", func(c *context.Context) {})
orderParty := app.Party("/order", func(context *context.Context) {
fmt.Println("orderParty->")
context.Next()
})
orderParty.Get("/login", func(c *context.Context) {})
orderParty.Get("/logout", func(c *context.Context) {})
orderParty.Get("/register", func(c *context.Context) {})
orderParty.Get("/...", func(c *context.Context) {})
orderParty.Get("/", func(c *context.Context) {})
app.Listen(":8080")
}
页面模版
app.RegisterView:注册视图
app.HandleDir:静态资源目录设置
ctx.View:渲染页面
package main
import (
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/context"
"net/http"
)
func main() {
app := iris.New()
//iris.Compression 是iris内部对IO数据进行压缩的模块,可以提高数据传输速度
app.Use(iris.Compression)
// 页面渲染配置
// 从"./views"目录下家在扩展名是"。html" 的所有模版
// 并使用标准的 "html/template"包进行解析
// 开发的时候每次修改模版都得启动应用
// Reload 设置为true,以便在每次请求时重新构建模版
app.RegisterView(iris.HTML("src/main/16_iris/views", ".html").Reload(true))
//静态资源目录文件
app.HandleDir("static", http.Dir("src/main/16_iris/static"))
app.Get("/index", func(context *context.Context) {
//跳转到指定的页面 / views / index.html
context.ViewData("msg", "hello world")
context.View("index.html")
})
//使用网络地址启动服务
app.Listen(":8080")
}
body{
background: blue;
}
alert(1)
中间件
错误处理
HTTP常见的状态码
100 | Continue | 继续。客户端应继续其请求 |
---|---|---|
101 | Switching Protocols | 切换协议。服务器根据客户端的请求切换协议。只能切换到更高级的协议,例如,切换到HTTP的新版本协议 |
200 | OK | 请求成功。一般用于GET与POST请求 |
201 | Created | 已创建。成功请求并创建了新的资源 |
202 | Accepted | 已接受。已经接受请求,但未处理完成 |
203 | Non-Authoritative Information | 非授权信息。请求成功。但返回的meta信息不在原始的服务器,而是一个副本 |
204 | No Content | 无内容。服务器成功处理,但未返回内容。在未更新网页的情况下,可确保浏览器继续显示当前文档 |
205 | Reset Content | 重置内容。服务器处理成功,用户终端(例如:浏览器)应重置文档视图。可通过此返回码清除浏览器的表单域 |
206 | Partial Content | 部分内容。服务器成功处理了部分GET请求 |
300 | Multiple Choices | 多种选择。请求的资源可包括多个位置,相应可返回一个资源特征与地址的列表用于用户终端(例如:浏览器)选择 |
301 | Moved Permanently | 永久移动。请求的资源已被永久的移动到新URI,返回信息会包括新的URI,浏览器会自动定向到新URI。今后任何新的请求都应使用新的URI代替,比如说我们下载的东西不再这个地址吗,需要去到新的地址 |
302 | Found | 临时移动。与301类似。但资源只是临时被移动。客户端应继续使用原有URI |
303 | See Other | 查看其它地址。与301类似。使用GET和POST请求查看 |
304 | Not Modified | 未修改。所请求的资源未修改,服务器返回此状态码时,不会返回任何资源。客户端通常会缓存访问过的资源,通过提供一个头信息指出客户端希望只返回在指定日期之后修改的资源 |
305 | Use Proxy | 使用代理。所请求的资源必须通过代理访问 |
306 | Unused | 已经被废弃的HTTP状态码 |
307 | Temporary Redirect | 临时重定向。与302类似。使用GET请求重定向 |
400 | Bad Request | 客户端请求的语法错误,服务器无法理解 |
401 | Unauthorized | 请求要求用户的身份认证 |
402 | Payment Required | 保留,将来使用 |
403 | Forbidden | 服务器理解请求客户端的请求,但是拒绝执行此请求 |
404 | Not Found | 服务器无法根据客户端的请求找到资源(网页)。通过此代码,网站设计人员可设置"您所请求的资源无法找到"的个性页面,请求的内容不存在 |
405 | Method Not Allowed | 客户端请求中的方法被禁止 |
406 | Not Acceptable | 服务器无法根据客户端请求的内容特性完成请求 |
407 | Proxy Authentication Required | 请求要求代理的身份认证,与401类似,但请求者应当使用代理进行授权 |
408 | Request Time-out | 服务器等待客户端发送的请求时间过长,超时 |
409 | Conflict | 服务器完成客户端的 PUT 请求时可能返回此代码,服务器处理请求时发生了冲突 |
410 | Gone | 客户端请求的资源已经不存在。410不同于404,如果资源以前有现在被永久删除了可使用410代码,网站设计人员可通过301代码指定资源的新位置 |
411 | Length Required | 服务器无法处理客户端发送的不带Content-Length的请求信息 |
412 | Precondition Failed | 客户端请求信息的先决条件错误 |
413 | Request Entity Too Large | 由于请求的实体过大,服务器无法处理,因此拒绝请求。为防止客户端的连续请求,服务器可能会关闭连接。如果只是服务器暂时无法处理,则会包含一个Retry-After的响应信息 |
414 | Request-URI Too Large | 请求的URI过长(URI通常为网址),服务器无法处理 |
415 | Unsupported Media Type | 服务器无法处理请求附带的媒体格式 |
416 | Requested range not satisfiable | 客户端请求的范围无效 |
417 | Expectation Failed | 服务器无法满足Expect的请求头信息 |
500 | Internal Server Error | 服务器内部错误,无法完成请求 |
501 | Not Implemented | 服务器不支持请求的功能,无法完成请求 |
502 | Bad Gateway | 作为网关或者代理工作的服务器尝试执行请求时,从远程服务器接收到了一个无效的响应 |
503 | Service Unavailable | 由于超载或系统维护,服务器暂时的无法处理客户端的请求。延时的长度可包含在服务器的Retry-After头信息中 |
504 | Gateway Time-out | 充当网关或代理的服务器,未及时从远端服务器获取请求 |
505 | HTTP Version not supported | 服务器不支持请求的HTTP协议的版本,无法完成处理 |
package main
import (
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/context"
"net/http"
)
func main() {
app := iris.New()
//iris.Compression 是iris内部对IO数据进行压缩的模块,可以提高数据传输速度
app.Use(iris.Compression)
app.RegisterView(iris.HTML("src/main/16_iris/views", ".html").Reload(true))
//静态资源目录文件
app.HandleDir("static", http.Dir("src/main/16_iris/static"))
//404
app.OnErrorCode(iris.StatusNotFound, not404)
//500
app.OnErrorCode(iris.StatusInternalServerError, func(c *context.Context) {
//500luoji
c.WriteString("500")
})
//301 重定向
//index
app.Get("/index", func(context *context.Context) {
login := true
if login {
context.ViewData("msg", "hello world")
context.View("index.html")
} else {
//登录逻辑 301 2
context.StatusCode(302)
context.Header("Location", "/login")
}
})
//login
app.Get("/login", func(c *context.Context) {
c.View("login.html")
})
//使用网络地址启动服务
app.Listen(":8080")
}
func not404(c *context.Context) {
//404逻辑
c.WriteString("404")
}
中间件
一般选择一个web框架时,会把是否支持中间件
中间件是否易用作为一个关键指标。
中间件可以作用于全局,可以用作用户认证、权限判断、跨域等多种功能。
同一功能
package main
import (
"fmt"
"github.com/kataras/iris/v12"
)
func main() {
app := iris.New()
app.Use(iris.Compression)
//全局中间件处理
app.Use(before)
app.Done(after)
//请求都可以通过多个处理器来处理
//app.Get("/index", before, index, after)
app.Get("/index", index)
app.Listen(":8080")
}
func before(ctx iris.Context) {
fmt.Println("before")
//交给下一个处理器处理
ctx.Next()
}
func index(ctx iris.Context) {
fmt.Println("index")
ctx.Next()
}
func after(ctx iris.Context) {
fmt.Println("after")
ctx.Next()
}
session
会话
会话:用户打开一个浏览器,点击了很多超链接,访问多个web资源,关闭浏览器,这个过程可以称之为会话
有状态会话:一个同学来过教室,下次再来教室,我们会知道这个同学,曾经来过,称之为有状态会话
保存会话的两种技术
cookie
- 客户端技术(响应,请求)
session
- 服务器技术,利用这个技术,可以保存用户的会话信息,我们可以把信息或者数据放在session中
常见:网站登录之后,下次就可以不用登录了,第二次访问直接就上去了
Iris提供了一个快速、功能齐全且易于使用的Session管理器
Iris的Sessions管理器依赖于它自己的kataras/iris/sessions包
这是一个sessions管理器。我们需要使用它来存储session数据
初始化sessions:
var session = sessions.New(sessions.Config{Cookie:"xxxxxx"})
然后使用中间件来运行session
,Sess.Start(ctx)
,Start
函数需要接收一个context
,然后我们定义一个字段hasLogin
,用来存储登录状态,如果hasLogin
为true
,我们就通过ctx.values().Set()
方法,将hasLogin
注入到context
中,方便后面的控制器判断和检查调用。
package main
import (
"fmt"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/context"
"github.com/kataras/iris/v12/sessions"
)
var (
cookie = "sessionId"
session = sessions.New(sessions.Config{Cookie: cookie})
)
func login(ctx iris.Context) {
//开启会话
session := session.Start(ctx)
//业务逻辑
//身份用户已验证
session.Set("authenticated", true)
fmt.Println("用户已经登录")
}
func loginout(ctx iris.Context) {
//开启会话
session := session.Start(ctx)
//业务逻辑
//身份用户已失效
session.Set("authenticated", false)
fmt.Println("用户已经退出")
}
func main() {
app := iris.New()
app.Use(iris.Compression)
//请求都可以通过多个处理器来处理
//app.Get("/index", before, index, after)
app.Get("/index", index)
app.Get("/login", login)
app.Get("/loginout", loginout)
//destroy方法,删除整个会话数据和Cookie
app.Get("/destroy", func(context *context.Context) {
session.Destroy(context)
})
app.Listen(":8080")
}
func index(ctx iris.Context) {
//检查用户是否已通过身份验证
auth, _ := session.Start(ctx).GetBoolean("authenticated")
if auth == false {
//未通过
ctx.StatusCode(iris.StatusForbidden)
fmt.Println("用户进入index")
return
}
ctx.WriteString("用户已经登录过了")
}