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

使用 Echo 框架进行基本身份验证

使用 Echo 框架进行基本身份验证

Go
沧海一幻觉 2022-06-01 17:51:23
尝试使用 Go 的 Echo 框架进行基本身份验证。找到了几段代码,但目前还没有完整的代码集。到目前为止有这个基本程序package mainimport (    "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"))}它提示输入用户名和密码,但经过身份验证后我得到未找到信息”使用 Echo 框架的基本身份验证的任何建议或工作代码链接将不胜感激。
查看完整描述

2 回答

?
牧羊人nacy

TA贡献1862条经验 获得超7个赞

除了 fstanis在这里回答的内容之外,我想指出您应该注意 echo group 对象的引用。


所以我认为你应该这样做


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。


查看完整回答
反对 回复 2022-06-01
?
撒科打诨

TA贡献1934条经验 获得超2个赞

您正在Group为您的路线注册一个内部回调。相反,您想在顶层注册组并向它们添加路由:


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

}))

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

    return c.HTML(http.StatusOK, html)

})


查看完整回答
反对 回复 2022-06-01
  • 2 回答
  • 0 关注
  • 189 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

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

帮助反馈 APP下载

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

公众号

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