如何忽略一个路由器进行使用Echo框架进行BasicAuth检查?

为了使用基本的身份验证来保护整个应用程序,这种方式可以对所有路由器都做些什么:


package main


import (

    "crypto/subtle"

    "net/http"


    "github.com/labstack/echo/v4"

    "github.com/labstack/echo/v4/middleware"

)


type Message struct {

    Status string `json:"status"`

}


func main() {

    e := echo.New()


    e.Use(middleware.BasicAuth(func(username, password string, c echo.Context) (bool, error) {

        if subtle.ConstantTimeCompare([]byte(username), []byte("username")) == 1 &&

            subtle.ConstantTimeCompare([]byte(password), []byte("password")) == 1 {

            return true, nil

        }

        return false, nil

    }))


    e.GET("/", func(c echo.Context) error {

        return c.String(http.StatusOK, "Hello, World!")

    })


    e.GET("/hello", func(c echo.Context) error {

        return c.String(http.StatusOK, "Hello")

    })


    e.GET("/healthcheck", func(c echo.Context) error {

        u := &Message{

            Status: "OK",

        }

        return c.JSON(http.StatusOK, u)

    })

    e.Logger.Fatal(e.Start(":8080"))

}

如果要忽略一个路由器 - 到其目标,该怎么办?/healthcheck


如果设置为除 /healthcheck 以外的每个路由器将解决此问题,但它需要许多代码。e.Use(middleware.BasicAuth)


开心每一天1111
浏览 154回答 1
1回答

冉冉说

您可以对路由进行分组package mainimport (    "crypto/subtle"    "net/http"    "github.com/labstack/echo/v4"    "github.com/labstack/echo/v4/middleware")type Message struct {    Status string `json:"status"`}func main() {    e := echo.New()    g := e.Group("/")    g.Use(middleware.BasicAuth(func(username, password string, c echo.Context) (bool, error) {        if subtle.ConstantTimeCompare([]byte(username), []byte("username")) == 1 &&            subtle.ConstantTimeCompare([]byte(password), []byte("password")) == 1 {            return true, nil        }        return false, nil    }))    g.GET("/", func(c echo.Context) error {        return c.String(http.StatusOK, "Hello, World!")    })    e.GET("/healthcheck", func(c echo.Context) error {        u := &Message{            Status: "OK",        }        return c.JSON(http.StatusOK, u)    })    e.Logger.Fatal(e.Start(":8080"))}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go