Home  >  Article  >  Backend Development  >  Analyze how to use golang iris

Analyze how to use golang iris

藏色散人
藏色散人forward
2021-07-02 14:02:192294browse

##Install iris
<span style="font-size: 14px;">go get github.com/kataras/iris<br></span>

Instance

Register a route to the service 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>

It can be achieved with a few lines of code, access http://localhost through the browser :8080/ping will return {"message":"pong"}

Use the Handle function to register methods, paths and corresponding processing functions

Add middleware

If we want to record the log information of all requests and also want to confirm whether the requested UA is allowed by us when calling the corresponding route, we can add it through the Use function. 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>

Analyze how to use golang iris

Using postman access to add User-Agent to the Header to access/ping can return the result normally, if the User-Agent is removed, it will return We set "No authorized for ping". Because we added iris's log middleware, the corresponding log information will be displayed on the terminal during access

Get the request parameters and display them in 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>

Get the parameters in the request

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

Set the value of variables in html

ctx.ViewData(key, value)

Route allows and prohibits external access

In actual use, sometimes some routes only It can be used internally and cannot be accessed externally. Can be set to offline by using 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>

Test:

<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

In actual Routes are classified in the application based on actual functions, such as users, books, community, etc.

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

/books/bookinfo
/books/chapterlist

For this type of route, they can be divided into the users group and the books group. There will be a common handler for the group to handle some common processing

<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 was used in the above example. All routes accessing the books group will first undergo auth authentication. The authentication method is username and password.

Visit http://localhost:8080/books/sfsg3234/bookinfo in postman

Set Authorization to Basic Auth, Username and Password to the values ​​in the program, Access will be answered correctly. Otherwise it will reply Unauthorized



For more golang related technical articles, please visit
Analyze how to use golang iris

golang

Tutorial column!

The above is the detailed content of Analyze how to use golang iris. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete