>  기사  >  백엔드 개발  >  golang 아이리스 사용법 분석

golang 아이리스 사용법 분석

藏色散人
藏色散人앞으로
2021-07-02 14:02:192226검색

를 사용하여 iris

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

instance

서비스 API에 대한 경로를 등록합니다. 몇 줄의 코드, 브라우저를 통해 http에 액세스합니다. ://localhost:8080/ping은 {"message":"pong"}을 반환합니다

Handle 함수를 사용하여 메서드, 경로 및 해당 처리 함수를 등록합니다

미들웨어 추가

기록하고 싶다면 모든 요청의 로그 정보를 다운로드하고 해당 경로 호출 시 요청한 UA가 허용되는지 확인하기 위해 사용 기능을 통해 해당 미들웨어를 추가할 수 있습니다
<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>

사용하세요. 헤더에 User-Agent를 추가하기 위한 postman 액세스 /ping에 액세스하면 정상적으로 결과가 반환될 수 있습니다. User-Agent가 제거되면 우리가 설정한 "No allowed for ping"이 반환됩니다. iris의 로그 미들웨어를 추가했기 때문에 접속 시 해당 로그 정보가 터미널에 표시됩니다

golang 아이리스 사용법 분석

요청 매개변수를 가져와 html

bookinfo.html
<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>

main.go에 표시합니다.

<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>

요청에서 매개변수 가져오기

<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>

html에서 변수 값 설정

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

route는 외부 액세스를 허용 및 금지합니다

실제 사용에서 일부 경로는 내부에서만 사용할 수 있습니다. 외부에서는 액세스할 수 없습니다.

ctx.ViewData(key, value)

그룹화 경로

를 사용하여 오프라인으로 설정할 수 있습니다. 실제 애플리케이션에서는 사용자, 도서, 커뮤니티 등 실제 기능에 따라 경로가 분류됩니다.

<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已经可以对外访问了

위 예에서는 Basicauth가 사용되었습니다. 도서 그룹에 액세스하는 모든 경로는 먼저 인증 인증을 받습니다. 인증 방법은 사용자 이름과 비밀번호입니다.

postman의 http://localhost:8080/books/sfsg3234/bookinfo를 방문하세요기본 인증에 대한 권한, 사용자 이름, 비밀번호를 프로그램의 값으로 설정하면 액세스가 올바르게 응답됩니다. 그렇지 않으면 Unauthorized


더 많은 golang 관련 기술 기사를 보려면

golang

튜토리얼 칼럼을 방문하세요!

위 내용은 golang 아이리스 사용법 분석의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 segmentfault.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제