Maison  >  Article  >  développement back-end  >  Analyser comment utiliser l'iris golang

Analyser comment utiliser l'iris golang

藏色散人
藏色散人avant
2021-07-02 14:02:192226parcourir

pour installer iris

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

instance

Enregistrer une route vers l'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 peut être réalisé avec quelques lignes de code , accédez à http via le navigateur ://localhost:8080/ping renverra {"message": "pong"}

Utilisez la fonction Handle pour enregistrer les méthodes, les chemins et les fonctions de traitement correspondantes

Ajouter un middleware

Si nous voulons enregistrer Téléchargez les informations du journal de toutes les demandes et espérons confirmer si l'UA demandé est autorisé par nous lors de l'appel de la route correspondante, vous pouvez ajouter le middleware correspondant via la fonction Utiliser

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

Analyser comment utiliser liris golang

Utiliser. L'accès du facteur pour ajouter l'agent utilisateur dans l'en-tête Accès /ping peut renvoyer des résultats normalement. Si l'agent utilisateur est supprimé, il renverra le "Non autorisé pour le ping" que nous avons défini. Parce que nous avons ajouté le middleware de journal d'iris, les informations de journal correspondantes seront affichées sur le terminal lors de l'accès.

<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>
Obtenir les paramètres dans la requête
<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>
Définir la valeur de la variable en HTML

ctx.Params().GetString("bookid")
route autorise et interdit l'accès externe

En utilisation réelle, parfois certaines routes ne peuvent être utilisées qu'en interne et n'est pas accessible depuis l'extérieur.

Peut être mis hors ligne en utilisant

ctx.ViewData(key, value)

itinéraire de regroupement

Dans les applications réelles, les itinéraires seront classés en fonction de fonctions réelles, telles que les utilisateurs, les livres, la communauté, etc.

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

Pour ce type d'itinéraires, vous pouvez les diviser en groupe d'utilisateurs et en groupe de livres. Il y aura un gestionnaire commun pour que le groupe gère certains traitements communs

<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 a été utilisé dans l'exemple ci-dessus. Tous les itinéraires accédant au groupe de livres seront d'abord soumis à une authentification d'authentification. La méthode d'authentification est le nom d'utilisateur et le mot de passe.

Visitez http://localhost:8080/books/sfsg3234/bookinfo dans postmanDéfinissez l'autorisation sur l'authentification de base, le nom d'utilisateur et le mot de passe sur les valeurs du programme, et l'accès recevra une réponse correcte. Sinon, non autorisé


Pour plus d'articles techniques liés au golang, veuillez visiter la colonne

golang


 !

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer