目录
安装iris" >安装iris
实例" >实例
注册一个route到服务的API" >注册一个route到服务的API
添加middleware" >添加middleware
取得请求参数,展示到html" >取得请求参数,展示到html
首页 后端开发 Golang 解析golang iris怎么使用

解析golang iris怎么使用

Jul 02, 2021 pm 02:02 PM
golang

安装iris

<span style="font-size: 14px;">go get github.com/kataras/iris<br></span>
登录后复制

实例

注册一个route到服务的API
<span style="font-size: 14px;">app := iris.New()<br><br>app.Handle("GET", "/ping", func(ctx iris.Context) {<br>    ctx.JSON(iris.Map{"message": "pong"})<br>})<br><br>app.Run(iris.Addr(":8080"))<br></span>
登录后复制

几行代码就可以实现,通过浏览器访问http://localhost:8080/ping会返回{"message":"pong"}

使用Handle函数可以注册方法,路径和对应的处理函数

添加middleware

如果我们希望记录下所有的请求的log信息还希望在调用相应的route时确认请求的UA是否是我们允许的可以通过Use函数添加相应的middleware

<span style="font-size: 14px;">package main<br/><br/>import (<br/>    "github.com/kataras/iris"<br/>    "github.com/kataras/iris/middleware/logger"<br/>)<br/><br/>func main() {<br/>    app := iris.New()<br/><br/>    app.Use(logger.New())<br/>    app.Use(checkAgentMiddleware)<br/><br/>    app.Handle("GET", "/ping", func(ctx iris.Context) {<br/>        ctx.JSON(iris.Map{"message": "pong"})<br/>    })<br/><br/>    app.Run(iris.Addr(":8080"))<br/>}<br/><br/>func checkAgentMiddleware(ctx iris.Context) {<br/>    ctx.Application().Logger().Infof("Runs before %s", ctx.Path())<br/>    user_agent := ctx.GetHeader("User-Agent")<br/><br/>    if user_agent != "pingAuthorized" {<br/>        ctx.JSON("No authorized for ping")<br/>        return<br/>    }<br/>    ctx.Next()<br/>}<br/></span>
登录后复制

8f394b9960535d63ea91f8092a2371b.png

使用postman访问在Header中添加User-Agent访问/ping可以正常返回结果,如果去掉User-Agent则会返回我们设定的"No authorized for ping"。因为我们添加了iris的log middleware所以在访问时会在终端显示相应的log信息

取得请求参数,展示到html

bookinfo.html

<span style="font-size: 14px;"><html><br/>    <head>Book information</head><br/>    <body><br/>        <h2>{{ .bookName }}</h2><br/>        <h1>{{ .bookID }}</h1><br/>        <h1>{{ .author }}</h1><br/>        <h1>{{ .chapterCount }}</h1><br/>    </body><br/></html><br/></span>
登录后复制

main.go

<span style="font-size: 14px;">package main<br/><br/>import "github.com/kataras/iris"<br/><br/>func main() {<br/>    app := iris.New()<br/><br/>    app.RegisterView(iris.HTML("./views", ".html"))<br/><br/>    app.Handle("GET", "/bookinfo/{bookid:string}", func(ctx iris.Context) {<br/>        bookID := ctx.Params().GetString("bookid")<br/><br/>        ctx.ViewData("bookName", "Master iris")<br/>        ctx.ViewData("bookID", bookID)<br/>        ctx.ViewData("author", "Iris expert")<br/>        ctx.ViewData("chapterCount", "40")<br/><br/>        ctx.View("bookinfo.html")<br/>    })<br/><br/>    app.Run(iris.Addr(":8080"))<br/>}<br/></span>
登录后复制

取得请求中带的参数

ctx.Params().GetString("bookid")
登录后复制

设置html中变量的值

ctx.ViewData(key, value)
登录后复制

route允许和禁止外部访问

实际使用中有时会有些route只能内部使用,对外访问不到。
可以通过使用 XXX_route.Method = iris.MethodNone设定为offline
内部调用通过使用函数 Context.Exec("NONE", "/XXX_yourroute")

main.go

<span style="font-size: 14px;">package main<br/><br/>import "github.com/kataras/iris"<br/><br/>import "strings"<br/><br/>func main() {<br/>    app := iris.New()<br/><br/>    magicAPI := app.Handle("NONE", "/magicapi", func(ctx iris.Context) {<br/>        if ctx.GetCurrentRoute().IsOnline() {<br/>            ctx.Writef("I&#39;m back!")<br/>        } else {<br/>            ctx.Writef("I&#39;ll be back")<br/>        }<br/>    })<br/><br/>    app.Handle("GET", "/onoffhandler/{method:string}/{state:string}", func(ctx iris.Context) {<br/>        changeMethod := ctx.Params().GetString("method")<br/>        state := ctx.Params().GetString("state")<br/><br/>        if changeMethod == "" || state == "" {<br/>            return<br/>        }<br/><br/>        if strings.Index(magicAPI.Path, changeMethod) == 1 {<br/>            settingState := strings.ToLower(state)<br/>            if settingState == "on" || settingState == "off" {<br/>                if strings.ToLower(state) == "on" && !magicAPI.IsOnline() {<br/>                    magicAPI.Method = iris.MethodGet<br/>                } else if strings.ToLower(state) == "off" && magicAPI.IsOnline() {<br/>                    magicAPI.Method = iris.MethodNone<br/>                }<br/><br/>                app.RefreshRouter()<br/><br/>                ctx.Writef("\n Changed magicapi to %s\n", state)<br/>            } else {<br/>                ctx.Writef("\n Setting state incorrect(\"on\" or \"off\") \n")<br/>            }<br/><br/>        }<br/>    })<br/><br/>    app.Handle("GET", "/execmagicapi", func(ctx iris.Context) {<br/>        ctx.Values().Set("from", "/execmagicapi")<br/><br/>        if !magicAPI.IsOnline() {<br/>            ctx.Exec("NONE", "/magicapi")<br/>        } else {<br/>            ctx.Exec("GET", "/magicapi")<br/>        }<br/>    })<br/><br/>    app.Run(iris.Addr(":8080"))<br/>}<br/></span>
登录后复制

测试:

<1>访问http://localhost:8080/magicapi,返回Not found。说明route magicapi对外无法访问
<2>访问http://localhost:8080/execmagicapi,返回I&#39;ll be back。在execmagicapi处理函数中会执行 ctx.Exec("GET", "/magicapi")调用offline的route magicapi。在magicapi中会判断自己是否offline,如果为offline则返回I&#39;ll be back。
<3>访问http://localhost:8080/onoffhandler/magicapi/on改变magicapi为online
<4>再次访问http://localhost:8080/magicapi,返回I&#39;m back!。说明route /mabicapi已经可以对外访问了
登录后复制

grouping route

在实际应用中会根据实际功能进行route的分类,例如users,books,community等。

/users/getuserdetail
/users/getusercharges
/users/getuserhistory

/books/bookinfo
/books/chapterlist
登录后复制

对于这类route可以把他们划分在users的group和books的group。对该group会有共通的handler处理共同的一些处理

<span style="font-size: 14px;">package main<br/><br/>import (<br/>    "time"<br/><br/>    "github.com/kataras/iris"<br/>    "github.com/kataras/iris/middleware/basicauth"<br/>)<br/><br/>func bookInfoHandler(ctx iris.Context) {<br/>    ctx.HTML("<h1>Calling bookInfoHandler </h1>")<br/>    ctx.HTML("<br/>bookID:" + ctx.Params().Get("bookID"))<br/>    ctx.Next()<br/>}<br/><br/>func chapterListHandler(ctx iris.Context) {<br/>    ctx.HTML("<h1>Calling chapterListHandler </h1>")<br/>    ctx.HTML("<br/>bookID:" + ctx.Params().Get("bookID"))<br/>    ctx.Next()<br/>}<br/><br/>func main() {<br/>    app := iris.New()<br/><br/>    authConfig := basicauth.Config{<br/>        Users:   map[string]string{"bookuser": "testabc123"},<br/>        Realm:   "Authorization required",<br/>        Expires: time.Duration(30) * time.Minute,<br/>    }<br/><br/>    authentication := basicauth.New(authConfig)<br/><br/>    books := app.Party("/books", authentication)<br/><br/>    books.Get("/{bookID:string}/bookinfo", bookInfoHandler)<br/>    books.Get("/chapterlist/{bookID:string}", chapterListHandler)<br/><br/>    app.Run(iris.Addr(":8080"))<br/>}<br/></span>
登录后复制

上例中使用了basicauth。对所有访问books group的routes都会先做auth认证。认证方式是username和password。

在postman中访问 http://localhost:8080/books/sfsg3234/bookinfo
设定Authorization为Basic Auth,Username和Password设定为程序中的值,访问会正确回复。否则会回复Unauthorized
6661008a75bf696824aeea79c78a65c.png

更多golang相关技术文章,请访问golang教程栏目!

以上是解析golang iris怎么使用的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

如何使用 Golang 安全地读取和写入文件? 如何使用 Golang 安全地读取和写入文件? Jun 06, 2024 pm 05:14 PM

在Go中安全地读取和写入文件至关重要。指南包括:检查文件权限使用defer关闭文件验证文件路径使用上下文超时遵循这些准则可确保数据的安全性和应用程序的健壮性。

如何为 Golang 数据库连接配置连接池? 如何为 Golang 数据库连接配置连接池? Jun 06, 2024 am 11:21 AM

如何为Go数据库连接配置连接池?使用database/sql包中的DB类型创建数据库连接;设置MaxOpenConns以控制最大并发连接数;设置MaxIdleConns以设定最大空闲连接数;设置ConnMaxLifetime以控制连接的最大生命周期。

Golang框架与Go框架:内部架构与外部特性对比 Golang框架与Go框架:内部架构与外部特性对比 Jun 06, 2024 pm 12:37 PM

GoLang框架与Go框架的区别体现在内部架构和外部特性上。GoLang框架基于Go标准库,扩展其功能,而Go框架由独立库组成,实现特定目的。GoLang框架更灵活,Go框架更容易上手。GoLang框架在性能上稍有优势,Go框架的可扩展性更高。案例:gin-gonic(Go框架)用于构建RESTAPI,而Echo(GoLang框架)用于构建Web应用程序。

如何在 Golang 中将 JSON 数据保存到数据库中? 如何在 Golang 中将 JSON 数据保存到数据库中? Jun 06, 2024 am 11:24 AM

可以通过使用gjson库或json.Unmarshal函数将JSON数据保存到MySQL数据库中。gjson库提供了方便的方法来解析JSON字段,而json.Unmarshal函数需要一个目标类型指针来解组JSON数据。这两种方法都需要准备SQL语句和执行插入操作来将数据持久化到数据库中。

如何找出 Golang 正则表达式匹配的第一个子字符串? 如何找出 Golang 正则表达式匹配的第一个子字符串? Jun 06, 2024 am 10:51 AM

FindStringSubmatch函数可找出正则表达式匹配的第一个子字符串:该函数返回包含匹配子字符串的切片,第一个元素为整个匹配字符串,后续元素为各个子字符串。代码示例:regexp.FindStringSubmatch(text,pattern)返回匹配子字符串的切片。实战案例:可用于匹配电子邮件地址中的域名,例如:email:="user@example.com",pattern:=@([^\s]+)$获取域名match[1]。

从前端转型后端开发,学习Java还是Golang更有前景? 从前端转型后端开发,学习Java还是Golang更有前景? Apr 02, 2025 am 09:12 AM

后端学习路径:从前端转型到后端的探索之旅作为一名从前端开发转型的后端初学者,你已经有了nodejs的基础,...

如何用 Golang 使用预定义时区? 如何用 Golang 使用预定义时区? Jun 06, 2024 pm 01:02 PM

Go语言中使用预定义时区包括以下步骤:导入"time"包。通过LoadLocation函数加载特定时区。在创建Time对象、解析时间字符串等操作中使用已加载的时区,进行日期和时间转换。使用不同时区的日期进行比较,以说明预定义时区功能的应用。

golang框架开发实战教程:常见疑问解答 golang框架开发实战教程:常见疑问解答 Jun 06, 2024 am 11:02 AM

Go框架开发常见问题解答:框架选择:取决于应用需求和开发者偏好,如Gin(API)、Echo(可扩展)、Beego(ORM)、Iris(性能)。安装和使用:使用gomod命令安装,导入框架并使用。数据库交互:使用ORM库,如gorm,建立数据库连接和操作。身份验证和授权:使用会话管理和身份验证中间件,如gin-contrib/sessions。实战案例:使用Gin框架构建一个简单的博客API,提供POST、GET等功能。

See all articles