您现在的位置是:群英 > 开发技术 > 编程语言
Golang中iris使用操作是什么,实际应用是怎样
Admin发表于 2022-08-06 17:56:44776 次浏览
在这篇文章中我们会学习到关于“Golang中iris使用操作是什么,实际应用是怎样”的知识,小编觉得挺不错的,现在分享给大家,也给大家做个参考,希望对大家学习或工作能有帮助。下面就请大家跟着小编的思路一起来学习一下吧。

安装iris

go get github.com/kataras/iris

实例

注册一个route到服务的API
app := iris.New()

app.Handle("GET", "/ping", func(ctx iris.Context) {
ctx.JSON(iris.Map{"message": "pong"})
})

app.Run(iris.Addr(":8080"))

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

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

添加middleware

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

package main

import (
"github.com/kataras/iris"
"github.com/kataras/iris/middleware/logger"
)

func main() {
app := iris.New()

app.Use(logger.New())
app.Use(checkAgentMiddleware)

app.Handle("GET", "/ping", func(ctx iris.Context) {
ctx.JSON(iris.Map{"message": "pong"})
})

app.Run(iris.Addr(":8080"))
}

func checkAgentMiddleware(ctx iris.Context) {
ctx.Application().Logger().Infof("Runs before %s", ctx.Path())
user_agent := ctx.GetHeader("User-Agent")

if user_agent != "pingAuthorized" {
ctx.JSON("No authorized for ping")
return
}
ctx.Next()
}

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

取得请求参数,展示到html

bookinfo.html

<html>
<head>Book information</head>
<body>
<h2>{{ .bookName }}</h2>
<h1>{{ .bookID }}</h1>
<h1>{{ .author }}</h1>
<h1>{{ .chapterCount }}</h1>
</body>
</html>

main.go

package main

import "github.com/kataras/iris"

func main() {
app := iris.New()

app.RegisterView(iris.HTML("./views", ".html"))

app.Handle("GET", "/bookinfo/{bookid:string}", func(ctx iris.Context) {
bookID := ctx.Params().GetString("bookid")

ctx.ViewData("bookName", "Master iris")
ctx.ViewData("bookID", bookID)
ctx.ViewData("author", "Iris expert")
ctx.ViewData("chapterCount", "40")

ctx.View("bookinfo.html")
})

app.Run(iris.Addr(":8080"))
}

取得请求中带的参数

ctx.Params().GetString("bookid")

设置html中变量的值

ctx.ViewData(key, value)

route允许和禁止外部访问

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

main.go

package main

import "github.com/kataras/iris"

import "strings"

func main() {
app := iris.New()

magicAPI := app.Handle("NONE", "/magicapi", func(ctx iris.Context) {
if ctx.GetCurrentRoute().IsOnline() {
ctx.Writef("I'm back!")
} else {
ctx.Writef("I'll be back")
}
})

app.Handle("GET", "/onoffhandler/{method:string}/{state:string}", func(ctx iris.Context) {
changeMethod := ctx.Params().GetString("method")
state := ctx.Params().GetString("state")

if changeMethod == "" || state == "" {
return
}

if strings.Index(magicAPI.Path, changeMethod) == 1 {
settingState := strings.ToLower(state)
if settingState == "on" || settingState == "off" {
if strings.ToLower(state) == "on" && !magicAPI.IsOnline() {
magicAPI.Method = iris.MethodGet
} else if strings.ToLower(state) == "off" && magicAPI.IsOnline() {
magicAPI.Method = iris.MethodNone
}

app.RefreshRouter()

ctx.Writef("\n Changed magicapi to %s\n", state)
} else {
ctx.Writef("\n Setting state incorrect(\"on\" or \"off\") \n")
}

}
})

app.Handle("GET", "/execmagicapi", func(ctx iris.Context) {
ctx.Values().Set("from", "/execmagicapi")

if !magicAPI.IsOnline() {
ctx.Exec("NONE", "/magicapi")
} else {
ctx.Exec("GET", "/magicapi")
}
})

app.Run(iris.Addr(":8080"))
}

测试:

<1>访问http://localhost:8080/magicapi,返回Not found。说明route magicapi对外无法访问
<2>访问http://localhost:8080/execmagicapi,返回I'll be back。在execmagicapi处理函数中会执行 ctx.Exec("GET", "/magicapi")调用offline的route magicapi。在magicapi中会判断自己是否offline,如果为offline则返回I'll be back。
<3>访问http://localhost:8080/onoffhandler/magicapi/on改变magicapi为online
<4>再次访问http://localhost:8080/magicapi,返回I'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处理共同的一些处理

package main

import (
"time"

"github.com/kataras/iris"
"github.com/kataras/iris/middleware/basicauth"
)

func bookInfoHandler(ctx iris.Context) {
ctx.HTML("<h1>Calling bookInfoHandler </h1>")
ctx.HTML("<br/>bookID:" + ctx.Params().Get("bookID"))
ctx.Next()
}

func chapterListHandler(ctx iris.Context) {
ctx.HTML("<h1>Calling chapterListHandler </h1>")
ctx.HTML("<br/>bookID:" + ctx.Params().Get("bookID"))
ctx.Next()
}

func main() {
app := iris.New()

authConfig := basicauth.Config{
Users: map[string]string{"bookuser": "testabc123"},
Realm: "Authorization required",
Expires: time.Duration(30) * time.Minute,
}

authentication := basicauth.New(authConfig)

books := app.Party("/books", authentication)

books.Get("/{bookID:string}/bookinfo", bookInfoHandler)
books.Get("/chapterlist/{bookID:string}", chapterListHandler)

app.Run(iris.Addr(":8080"))
}

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

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


到此这篇关于“Golang中iris使用操作是什么,实际应用是怎样”的文章就介绍到这了,感谢各位的阅读,更多相关Golang中iris使用操作是什么,实际应用是怎样内容,欢迎关注群英网络资讯频道,小编将为大家输出更多高质量的实用文章!

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。

标签: iris使用
相关信息推荐
2022-09-16 17:55:38 
摘要:用到的技术:1、vue.js,vue-cli工程的核心,主要特点是双向数据绑定和组件系统;2、vue-router,路由框架;3、vuex,vue应用项目开发的状态管理器;4、axios,用于发起GET、或POST等http请求;5、vux,专为vue设计的移动端UI组件库;6、emit.js,用于vue事件机制的管理;7、webpack,模块加载和vue-cli工程打包器。
2022-01-27 21:01:27 
摘要:这篇文章我们来了解HTML中背景图透明度的设置,有时候我们在使用背景图片的时候,想要降低一点透明度,但又不想每张图片单独设置,那么使用opacity属性或者filter属性就能很好的解决。下文有详细的介绍,有需要的朋友可以参考,接下来就跟随小编来一起学习一下吧!
2022-06-16 09:27:26 
摘要:在PHP中,单例是一个类有且只有一个实例的意思,是指整个应用中的某个类只有一个对象实例的设计模式;单例模式中自行实例化会向整个系统全局提供这个实例,不会创建实例副本,而是会向单例类内部存储的实例返回一个引用。
云活动
推荐内容
热门关键词
热门信息
群英网络助力开启安全的云计算之旅
立即注册,领取新人大礼包
  • 联系我们
  • 24小时售后:4006784567
  • 24小时TEL :0668-2555666
  • 售前咨询TEL:400-678-4567

  • 官方微信

    官方微信
Copyright  ©  QY  Network  Company  Ltd. All  Rights  Reserved. 2003-2019  群英网络  版权所有   茂名市群英网络有限公司
增值电信经营许可证 : B1.B2-20140078   粤ICP备09006778号
免费拨打  400-678-4567
免费拨打  400-678-4567 免费拨打 400-678-4567 或 0668-2555555
微信公众号
返回顶部
返回顶部 返回顶部