搜索
首页后端开发GolangGolang 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 中处理该中间件。

以上是Golang Gin:标题已经写好了。想要用 200 覆盖状态代码 301的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:stackoverflow。如有侵权,请联系admin@php.cn删除
去其他语言:比较分析去其他语言:比较分析Apr 28, 2025 am 12:17 AM

goisastrongchoiceforprojectsneedingsimplicity,绩效和引发性,butitmaylackinadvancedfeatures and ecosystemmaturity.1)

比较以其他语言的静态初始化器中的初始化功能比较以其他语言的静态初始化器中的初始化功能Apr 28, 2025 am 12:16 AM

Go'sinitfunctionandJava'sstaticinitializersbothservetosetupenvironmentsbeforethemainfunction,buttheydifferinexecutionandcontrol.Go'sinitissimpleandautomatic,suitableforbasicsetupsbutcanleadtocomplexityifoverused.Java'sstaticinitializersoffermorecontr

GO中初始功能的常见用例GO中初始功能的常见用例Apr 28, 2025 am 12:13 AM

thecommonusecasesfortheinitfunctionoare:1)加载configurationfilesbeforeThemainProgramStarts,2)初始化的globalvariables和3)runningpre-checkSorvalidationsbeforEtheprofforeTheProgrecce.TheInitFunctionIsautefunctionIsautomentycalomationalmatomatimationalycalmatemationalcalledbebeforethemainfuniinfuninfuntuntion

GO中的频道:掌握际际交流GO中的频道:掌握际际交流Apr 28, 2025 am 12:04 AM

ChannelsarecrucialingoforenablingsafeandefficityCommunicationBetnewengoroutines.theyfacilitateSynChronizationAndManageGoroutIneLifeCycle,EssentialforConcurrentProgramming.ChannelSallSallSallSallSallowSallowsAllowsEnderDendingAndReceivingValues,ActassignalsignalsforsynChronization,and actassignalsynChronization and andsupppor

包装错误:将上下文添加到错误链中包装错误:将上下文添加到错误链中Apr 28, 2025 am 12:02 AM

在Go中,可以通过errors.Wrap和errors.Unwrap方法来包装错误并添加上下文。1)使用errors包的新功能,可以在错误传播过程中添加上下文信息。2)通过fmt.Errorf和%w包装错误,帮助定位问题。3)自定义错误类型可以创建更具语义化的错误,增强错误处理的表达能力。

使用GO开发时的安全考虑使用GO开发时的安全考虑Apr 27, 2025 am 12:18 AM

Gooffersrobustfeaturesforsecurecoding,butdevelopersmustimplementsecuritybestpracticeseffectively.1)UseGo'scryptopackageforsecuredatahandling.2)Manageconcurrencywithsynchronizationprimitivestopreventraceconditions.3)SanitizeexternalinputstoavoidSQLinj

了解GO的错误接口了解GO的错误接口Apr 27, 2025 am 12:16 AM

Go的错误接口定义为typeerrorinterface{Error()string},允许任何实现Error()方法的类型被视为错误。使用步骤如下:1.基本检查和记录错误,例如iferr!=nil{log.Printf("Anerroroccurred:%v",err)return}。2.创建自定义错误类型以提供更多信息,如typeMyErrorstruct{MsgstringDetailstring}。3.使用错误包装(自Go1.13起)来添加上下文而不丢失原始错误信息,

并发程序中的错误处理并发程序中的错误处理Apr 27, 2025 am 12:13 AM

对效率的Handleerrorsinconcurrentgopragrs,UsechannelstocommunicateErrors,EmparterRorwatchers,InsterTimeouts,UsebufferedChannels和Provideclearrormessages.1)USEchannelelStopassErstopassErrorsErtopassErrorsErrorsFromGoroutInestotheStothemainfunction.2)

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器