卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章34144本站已运行391

Golang Gin:标题已经写好了。想要用 200 覆盖状态代码 301

golang gin:标题已经写好了。想要用 200 覆盖状态代码 301

问题内容

我正在开发一个控制面板,并雇用了一些人来为我构建它。他们都逃走了,我只剩下清理意大利面了。

我需要做的是:

  • 拉出登录页面
  • 检查登录信息和发布表单
  • 发布成功后,重定向至仪表板页面

只是一个简单的登录过程。问题是,当登录成功时,控制台进入此重定向循环,如下所示:

[gin] 2023/02/21 - 15:43:32 | 301 |  1.224601041s |             ::1 | post     "/login"
[gin-debug] [warning] headers were already written. wanted to override status code 301 with 200
[gin] 2023/02/21 - 15:43:33 | 200 |    787.3905ms |             ::1 | get      "/dashboard"
[gin-debug] [warning] headers were already written. wanted to override status code 301 with 200
[gin] 2023/02/21 - 15:43:33 | 200 |  197.989875ms |             ::1 | get      "/login"
[gin-debug] [warning] headers were already written. wanted to override status code 301 with 200
[gin] 2023/02/21 - 15:43:34 | 200 |  817.293166ms |             ::1 | get      "/dashboard"
[gin-debug] [warning] headers were already written. wanted to override status code 301 with 200
[gin] 2023/02/21 - 15:43:34 | 200 |  206.107791ms |             ::1 | get      "/login"
[gin-debug] [warning] headers were already written. wanted to override status code 301 with 200
[gin] 2023/02/21 - 15:43:35 | 200 |  792.954375ms |             ::1 | get      "/dashboard"
[gin-debug] [warning] headers were already written. wanted to override status code 301 with 200
[gin] 2023/02/21 - 15:43:35 | 200 |  201.972708ms |             ::1 | get      "/login"
[gin-debug] [warning] headers were already written. wanted to override status code 301 with 200
[gin] 2023/02/21 - 15:43:36 | 200 |  840.773625ms |             ::1 | get      "/dashboard"
[gin-debug] [warning] headers were already written. wanted to override status code 301 with 200
[gin] 2023/02/21 - 15:43:36 | 200 |  198.680125ms |             ::1 | get      "/login"
[gin-debug] [warning] headers were already written. wanted to override status code 301 with 200
[gin] 2023/02/21 - 15:43:37 | 200 |  897.679708ms |             ::1 | get      "/dashboard"
[gin-debug] [warning] headers were already written. wanted to override status code 301 with 200
[gin] 2023/02/21 - 15:43:37 | 200 |  200.759917ms |             ::1 | get      "/login"
[gin-debug] [warning] headers were already written. wanted to override status code 301 with 200
[gin] 2023/02/21 - 15:43:38 | 200 |   795.39975ms |             ::1 | get      "/dashboard"
[gin-debug] [warning] headers were already written. wanted to override status code 301 with 200
[gin] 2023/02/21 - 15:43:38 | 200 |     196.538ms |             ::1 | get      "/login"
[gin-debug] [warning] headers were already written. wanted to override status code 301 with 200
[gin] 2023/02/21 - 15:43:39 | 200 |  844.680709ms |             ::1 | get      "/dashboard"
[gin-debug] [warning] headers were already written. wanted to override status code 301 with 200
[gin] 2023/02/21 - 15:43:39 | 200 |  180.598084ms |             ::1 | get      "/login"
[gin-debug] [warning] headers were already written. wanted to override status code 301 with 200
[gin] 2023/02/21 - 15:43:40 | 200 |  814.666208ms |             ::1 | get      "/dashboard"
[gin-debug] [warning] headers were already written. wanted to override status code 301 with 200
[gin] 2023/02/21 - 15:43:40 | 200 |     210.281ms |             ::1 | get      "/login"

现在,由于我正在填补老开发人员的空缺,所以我仍在学习/golang 和 gin 的新手,所以对我来说,这只是裸露的......

据我了解,main()正在配置路由、中间件、加载模板然后运行引擎。

ma​​in.go

func main() {
    //gin.setmode(gin.releasemode) // uncomment for production

    // startup tasks
    startup()
    logging.loginfo("ran startup tasks...")

    // configure engine
    hostport := fmt.sprintf(
        "%s:%d",
        datamanagers.loadconfig().bshost,
        datamanagers.loadconfig().bsport)
    webengine := gin.default()
    webengine.settrustedproxies([]string{hostport})
    logging.loginfo("configured engine...")

    // load middleware
    store := cookie.newstore([]byte(randstr.string(64)))
    webengine.use(sessions.sessions("session", store))
    webengine.use(errorhandler.errorshandler500())
    logging.loginfo("loaded middleware...")

    // configure routes
    pubroutes := webengine.group("/")
    privroutes := webengine.group("/")
    routes.publicroutes(pubroutes)
    privroutes.use(middleware.authrequired)
    routes.privateroutes(privroutes)
    logging.loginfo("configured routes...")

    // non routables
    webengine.noroute(errorhandler.errorshandler404())
    logging.loginfo("configured non-routables...")

    // load template files
    loadtemplates(webengine)
    logging.loginfo("loaded templates...")

    // start the gin engine
    err := webengine.run(hostport)
    logging.loginfo("...blocksuite-webui loaded")
    logging.catch(err)
}

当访问 / 时,我会被重定向到 /login,这会弹出登录表单。

我使用有效凭据提交表单,它会将我重定向到 /dashboard。我不知道成功登录后重定向是否正确,这就是原始开发人员所做的并且工作正常。

routes.go

func publicroutes(webengine *gin.routergroup) {
    webengine.get("/login", entry.logingethandler)
    webengine.post("/login", entry.loginposthandler)
    webengine.get("/", other.indexgethandler())
}
func privateroutes(webengine *gin.routergroup) {
    dashboardroutes := webengine.group("/dashboard")
    {
        dashboardroutes.get("/", dashboard.dashboardgethandler)
    }
}

login.go

func logingethandler(context *gin.context) {
    user := utility.getusersession(context).get("useremail")
    if user != nil {
        context.redirect(http.statusmovedpermanently, "/dashboard")
    }
    context.html(http.statusok, "login.html", gin.h{
        "sitekey":    datamanagers.getrecaptchasettings().sitekey,
        "enabled":    datamanagers.getrecaptchasettings().enabled,
        "content":    "",
        "success":    "",
        "serverlogo": brand.getbrandlogo(),
        "title":      "welcome back",
    })
}
func loginposthandler(context *gin.context) {
    user := utility.getusersession(context).get("useremail")
    if user != nil {
        context.redirect(http.statusmovedpermanently, "/dashboard")
        //return
    }
    useremail := utility.sanitize(context.postform("email"))
    password := utility.sanitize(context.postform("password"))
    rememberme := utility.sanitize(context.postform("rememberme"))
    //captcha := context.postform("g-recaptcha-response")
    if !utility.isemailvalid(useremail) {
        context.html(http.statusbadrequest, "login.html", gin.h{"content": "please enter a valid email address"})
        return
    }
    /*if helpers2.recaptchacheck(captcha) || datamanagers.getconfig().sitekey != "" {
        // success
    } else {
        if datamanagers.getconfig().enabled {
            context.html(http.statusbadrequest, "login.html", gin.h{"content": "please verify captcha"})
            return
        }
    }*/
    if utility.emptyuserpass(useremail, password) {
        context.html(http.statusbadrequest, "login.html", gin.h{"content": "email and password cannot be empty"})
        return
    }

    if utility.checkforwhitespaces(useremail, password) != nil {
        context.html(http.statusbadrequest, "login.html", gin.h{"content": "username and password can't contain spaces"})
        return
    }
    if !utility.checkuserpass(useremail, password) {
        context.html(http.statusunauthorized, "login.html", gin.h{"content": "incorrect username or password"})
        return
    }
    utility.newusersession(context, useremail)
    if rememberme == "yes" {
        utility.setsessionage(context)
    }
    context.redirect(http.statusmovedpermanently, "/dashboard")
}

然后,应该加载 /dashboard 页面。

dashboard.go

func dashboardgethandler(context *gin.context) {
    user := utility.getusersession(context).get("useremail")
    db := datamanagers.getdb()
    if user == nil {
        context.redirect(http.statusmovedpermanently, "/login")
    }
    [...]
    context.html(http.statusok, "dashboard.html", gin.h{
        "info":       info,
        "imageurl":   utility.getimage(user),
        "serverlogo": brand.getbrandicon(),
        "title":      "dashboard",
        "servername": datamanagers.getserverinfo().servername,
    })
}

(在 dashboard.go 代码中,我省略了将数据拉入仪表板的代码,因为它很长,并且认为没有必要。)

  • 我已经注释掉了dashboard.go 中的所有数据查询,并添加了一个简单的“hi”响应,但它仍然进行了重定向外观。所以,我知道这个 gofile 提取数据的方式没有任何问题。
  • 我尝试使用不同的 http 响应代码,例如 http.statusok 并且没有骰子。
  • 我在dashboard.go中验证了会话数据确实正在写入和保存。当加载仪表板 get 处理函数时,我能够输出会话数据。所以,我知道会话运行良好。
  • 我更改了处理程序的编写方式。以前,它的编码如下:
func DashboardGetHandler() gin.HandlerFunc {
    return func(context *gin.Context) {
    [...]
    }
}

我完全没有想法,不知道接下来该去哪里。谢谢!


正确答案


感谢所有提供帮助的人。我与前任开发人员取得了联系,他帮助我找出了问题所在。

在他的代码中,他创建了一个中间件函数,由于某种原因,该函数再次检查会话。那段代码正在检查会话 cookie 中不存在的旧变量。因此,我被踢回登录屏幕。

因此,我所做的就是删除该中间件,因为无论如何我都是在 login.go 中处理该中间件。

卓越飞翔博客
上一篇: 检查不同 Go Map 类型中的重复键
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏