add some helper methods for redirect and setting cookie

This commit is contained in:
maddalax 2024-10-20 10:21:37 -05:00
parent c32fa1bccd
commit b6d901fadf
3 changed files with 17 additions and 3 deletions

View file

@ -9,8 +9,7 @@ func GetUserOrRedirect(ctx *h.RequestContext) (db.User, bool) {
user, err := GetUserFromSession(ctx)
if err != nil {
ctx.Response.Header().Set("Location", "/login")
ctx.Response.WriteHeader(302)
ctx.Redirect("/login", 302)
return db.User{}, false
}

View file

@ -68,7 +68,7 @@ func WriteSessionCookie(ctx *h.RequestContext, session CreatedSession) {
Expires: session.Expiration,
Path: "/",
}
ctx.Response.Header().Add("Set-Cookie", cookie.String())
ctx.SetCookie(&cookie)
}
func GenerateSessionID() (string, error) {

View file

@ -33,6 +33,21 @@ func GetRequestContext(r *http.Request) *RequestContext {
return r.Context().Value(RequestContextKey).(*RequestContext)
}
func (c *RequestContext) SetCookie(cookie *http.Cookie) {
http.SetCookie(c.Response, cookie)
}
func (c *RequestContext) Redirect(path string, code int) {
if code == 0 {
code = http.StatusTemporaryRedirect
}
if code < 300 || code > 399 {
code = http.StatusTemporaryRedirect
}
c.Response.Header().Set("Location", path)
c.Response.WriteHeader(code)
}
func (c *RequestContext) IsHttpPost() bool {
return c.Request.Method == http.MethodPost
}