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

标签 go

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

相关文章:

go - 从 YAML 对象列表创建 API 对象

go - 在 Go 中重复函数调用的 For 循环

go - 设置一个最大年龄的cookie;最大年龄丢失

database - 如何解决多并发时的TIME_WAIT状态问题?

firebase - 在 Golang 中仅使用环境变量初始化 Firebase Admin SDK

go - 如何在 Golang 中使用 gobuffalo/packr

javascript - 在两个 Web Worker 中具有相同的 WebAssembly 实例

go - 如何 "bridge"writer 和 reader in go

for-loop - for range 的性能

go - 在 go 中使用空接口(interface)