为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
开心每一天1111 2022-08-15 17:35:17
为了使用基本的身份验证来保护整个应用程序,这种方式可以对所有路由器都做些什么: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()    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)
查看完整描述

1 回答

?
冉冉说

TA贡献1877条经验 获得超1个赞

您可以对路由进行分组


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

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

}


查看完整回答
反对 回复 2022-08-15
  • 1 回答
  • 0 关注
  • 153 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号