


Golang Gin: The title is already written. Want to override status code 301 with 200
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"
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) }
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) } }
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") }
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, }) }
(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) { [...] } }
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!

Goisastrongchoiceforprojectsneedingsimplicity,performance,andconcurrency,butitmaylackinadvancedfeaturesandecosystemmaturity.1)Go'ssyntaxissimpleandeasytolearn,leadingtofewerbugsandmoremaintainablecode,thoughitlacksfeatureslikemethodoverloading.2)Itpe

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

ThecommonusecasesfortheinitfunctioninGoare:1)loadingconfigurationfilesbeforethemainprogramstarts,2)initializingglobalvariables,and3)runningpre-checksorvalidationsbeforetheprogramproceeds.Theinitfunctionisautomaticallycalledbeforethemainfunction,makin

ChannelsarecrucialinGoforenablingsafeandefficientcommunicationbetweengoroutines.Theyfacilitatesynchronizationandmanagegoroutinelifecycle,essentialforconcurrentprogramming.Channelsallowsendingandreceivingvalues,actassignalsforsynchronization,andsuppor

In Go, errors can be wrapped and context can be added via errors.Wrap and errors.Unwrap methods. 1) Using the new feature of the errors package, you can add context information during error propagation. 2) Help locate the problem by wrapping errors through fmt.Errorf and %w. 3) Custom error types can create more semantic errors and enhance the expressive ability of error handling.

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

Go's error interface is defined as typeerrorinterface{Error()string}, allowing any type that implements the Error() method to be considered an error. The steps for use are as follows: 1. Basically check and log errors, such as iferr!=nil{log.Printf("Anerroroccurred:%v",err)return}. 2. Create a custom error type to provide more information, such as typeMyErrorstruct{MsgstringDetailstring}. 3. Use error wrappers (since Go1.13) to add context without losing the original error message,

ToeffectivelyhandleerrorsinconcurrentGoprograms,usechannelstocommunicateerrors,implementerrorwatchers,considertimeouts,usebufferedchannels,andprovideclearerrormessages.1)Usechannelstopasserrorsfromgoroutinestothemainfunction.2)Implementanerrorwatcher


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

WebStorm Mac version
Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1
Easy-to-use and free code editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
