为了使用基本的身份验证来保护整个应用程序,这种方式可以对所有路由器都做些什么:
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)
冉冉说
相关分类