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

尝试使用 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"))

}

它提示输入用户名和密码,但经过身份验证后我得到


未找到信息”


使用 Echo 框架的基本身份验证的任何建议或工作代码链接将不胜感激。


沧海一幻觉
浏览 190回答 2
2回答

牧羊人nacy

除了 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。

撒科打诨

您正在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)})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go