搜尋
首頁後端開發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()正在設定路由、中間件、載入模板然後運行引擎。

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)
}

當存取 / 時,我會被重新導向到 /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刪除
與GO接口鍵入斷言和類型開關與GO接口鍵入斷言和類型開關May 02, 2025 am 12:20 AM

Gohandlesinterfacesandtypeassertionseffectively,enhancingcodeflexibilityandrobustness.1)Typeassertionsallowruntimetypechecking,asseenwiththeShapeinterfaceandCircletype.2)Typeswitcheshandlemultipletypesefficiently,usefulforvariousshapesimplementingthe

使用errors.is和錯誤。使用errors.is和錯誤。May 02, 2025 am 12:11 AM

Go語言的錯誤處理通過errors.Is和errors.As函數變得更加靈活和可讀。 1.errors.Is用於檢查錯誤是否與指定錯誤相同,適用於錯誤鏈的處理。 2.errors.As不僅能檢查錯誤類型,還能將錯誤轉換為具體類型,方便提取錯誤信息。使用這些函數可以簡化錯誤處理邏輯,但需注意錯誤鏈的正確傳遞和避免過度依賴以防代碼複雜化。

在GO中進行性能調整:優化您的應用程序在GO中進行性能調整:優化您的應用程序May 02, 2025 am 12:06 AM

tomakegoapplicationsRunfasterandMorefly,useProflingTools,leverageConCurrency,andManageMoryfectily.1)usepprofforcpuorforcpuandmemoryproflingtoidentifybottlenecks.2)upitizegorizegoroutizegoroutinesandchannelstoparalletaparelalyizetasksandimproverperformance.3)

GO的未來:趨勢和發展GO的未來:趨勢和發展May 02, 2025 am 12:01 AM

go'sfutureisbrightwithtrendslikeMprikeMprikeTooling,仿製藥,雲 - 納蒂維德象,performanceEnhancements,andwebassemblyIntegration,butchallengeSinclainSinClainSinClainSiNgeNingsImpliCityInsImplicityAndimimprovingingRornhandRornrorlling。

了解Goroutines:深入研究GO的並發了解Goroutines:深入研究GO的並發May 01, 2025 am 12:18 AM

goroutinesarefunctionsormethodsthatruncurranceingo,啟用效率和燈威量。 1)shememanagedbodo'sruntimemultimusingmultiplexing,允許千sstorunonfewerosthreads.2)goroutinessimproverentimensImproutinesImproutinesImproveranceThroutinesImproveranceThrountinesimproveranceThroundinesImproveranceThroughEasySytaskParallowalizationAndeff

了解GO中的初始功能:目的和用法了解GO中的初始功能:目的和用法May 01, 2025 am 12:16 AM

purposeoftheInitfunctionoIsistoInitializeVariables,setUpConfigurations,orperformneccesSetarySetupBeforEtheMainFunctionExeCutes.useInitby.UseInitby:1)placingitinyourcodetorunautoamenationally oneraty oneraty oneraty on inity in ofideShortAndAndAndAndForemain,2)keepitiTshortAntAndFocusedonSimImimpletasks,3)

了解GO界面:綜合指南了解GO界面:綜合指南May 01, 2025 am 12:13 AM

Gointerfacesaremethodsignaturesetsthattypesmustimplement,enablingpolymorphismwithoutinheritanceforcleaner,modularcode.Theyareimplicitlysatisfied,usefulforflexibleAPIsanddecoupling,butrequirecarefulusetoavoidruntimeerrorsandmaintaintypesafety.

從恐慌中恢復:何時以及如何使用recover()從恐慌中恢復:何時以及如何使用recover()May 01, 2025 am 12:04 AM

在Go中使用recover()函數可以從panic中恢復。具體方法是:1)在defer函數中使用recover()捕獲panic,避免程序崩潰;2)記錄詳細的錯誤信息以便調試;3)根據具體情況決定是否恢復程序執行;4)謹慎使用,以免影響性能。

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

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境