尝试使用Go的Echo框架使基本身份验证起作用。已经找到了几段代码,但是到目前为止还没有找到完整的代码集。
到目前为止有这个基本程序
package main
import (
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
"net/http"
)
func main() {
var html string;
// Echo instance
e := echo.New()
// Route => handler
e.GET("/", func(c echo.Context) error {
e.Group("/").Use(middleware.BasicAuth(func(username, password string, c echo.Context) (bool, error) {
if username == "user" && password == "password" {
html ="Authenticated"
return true, nil
}
return false, nil
}))
return c.HTML(http.StatusOK, html)
})
// Start server
e.Logger.Fatal(e.Start(":1323"))
}
它提示输入用户名和密码,但是经过身份验证后,我得到了
message "Not Found"
希望使用Echo框架的基本身份验证提供任何建议或链接到工作代码。
最佳答案
除了fstanis回答here之外,我想指出的是,您在引用echo组对象时应格外小心。
所以我认为你应该这样做
e := echo.New()
g := e.Group("")
g.Use(middleware.BasicAuth(func(username, password string, c echo.Context) (bool, error) {
if username == "joe" && password == "secret" {
return true, nil
}
return false, nil
}))
// note that it was previously referring to the echo instance, not group.
g.GET("/", func(c echo.Context) error {
return c.HTML(http.StatusOK, html)
})
请注意,
g
指向组e.Group("")
,这确保GET“/”的处理程序将返回正确的html
。因此,对于将基本身份验证中间件应用于Group还是Echo e
的根实例,没有任何歧义。
关于go - 使用Echo框架进行基本身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61719745/