Home > Backend Development > Golang > Golang Gin: The title is already written. Want to override status code 301 with 200

Golang Gin: The title is already written. Want to override status code 301 with 200

PHPz
Release: 2024-02-06 10:18:08
forward
581 people have browsed it

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

Question content

I am developing a control panel and hired some people to build it for me. They all ran away and I was left cleaning the pasta.

What I need to do is:

  • Pull out the login page
  • Check login information and post form
  • After successful publishing, redirect to the dashboard page

Just a simple login process. The problem is that when the login is successful, the console goes into this redirect loop like this:

[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"
Copy after login

Now, I'm still learning/new to golang and gin since I'm filling in for an older developer, so for me this is just bare...

As far as I understand, main() is configuring routing, middleware, loading templates and then running the engine.

main.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)
}
Copy after login

When visiting / I am redirected to /login which brings up the login form.

I submit the form with valid credentials and it redirects me to /dashboard. I don't know if redirecting after successful login is correct, that's what the original developer did and it works fine.

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)
    }
}
Copy after login

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")
}
Copy after login

Then, the /dashboard page should load.

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,
    })
}
Copy after login

(In the dashboard.go code, I omitted the code that pulls the data into the dashboard because it was long and deemed unnecessary.)

  • I've commented out all the data queries in dashboard.go and added a simple "hi" response, but it still makes the redirect look. So, I know there's nothing wrong with the way this gofile extracts the data.
  • I tried using different http response codes such as http.statusok and no dice.
  • I verified in dashboard.go that the session data is indeed being written and saved. When loading the dashboard get handler I am able to output the session data. So, I know the session is running fine.
  • I changed the way the handler is written. Previously, it was encoded as follows:
func DashboardGetHandler() gin.HandlerFunc {
    return func(context *gin.Context) {
    [...]
    }
}
Copy after login

I have absolutely no idea where to go next. Thanks!


Correct answer


Thanks to everyone who helped. I got in touch with the previous developer and he helped me figure out the problem.

In his code he created a middleware function which for some reason checks the session again. That code is checking for an old variable in the session cookie that doesn't exist. So I'm kicked back to the login screen.

So what I did was remove that middleware since I was handling it in login.go anyway.

The above is the detailed content of Golang Gin: The title is already written. Want to override status code 301 with 200. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template