为了使用基本身份验证来保护整个应用程序,这种方式可以为所有路由器做:
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
对其目标,怎么办?
如果设置e.Use(middleware.BasicAuth)
到除/healthcheck之外的每个路由器将解决问题,但它需要很多代码。
最佳答案
您可以 Group
路线
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"))
}
关于go - 如何忽略一个路由器以使用 Echo 框架进行 BasicAuth 检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66609418/