Home > Software design >  r.Request.cookie() not working and if I use r.Response.request() it panic
r.Request.cookie() not working and if I use r.Response.request() it panic

Time:04-13

First I don't know if recent updates of go doesn't work anymore with r.Request.Cookie() but it seems that this func doesn't exist anymore... So I came across r.Response.Request.Cookie() but as soon as I open the page it crash.

This is my code:

package main

import (
    "io"
    "log"
    "net/http"

    uuid "github.com/nu7hatch/gouuid"
)

func main() {
    r := http.NewServeMux()

    r.HandleFunc("/", index)

    http.ListenAndServe(":80", r)

}

func index(w http.ResponseWriter, req *http.Request) {
    c, err := req.Response.Request.Cookie("session-id")
    if err != nil {
        cid, _ := uuid.NewV4()
        c := &http.Cookie{
            Name:  "session-id",
            Value: cid.String(),
        }
        http.SetCookie(w, c)
    }
    log.Fatal(err)

    io.WriteString(w, c.String())
}

CodePudding user response:

In c, err := req.Response.Request.Cookie("session-id") The Request will be nil as it's already consumed, You can go with req.Cookie("cookie-name") directly.

CodePudding user response:

The tutorial I was whatching was likely outdated. The updated working code is:

cookie, err := req.Cookie("session-id")
if err == http.ErrNoCookie {
c := &http.Cookie{
    Name:     "session-id",
    Value:    cid.String(),
    MaxAge:   300,
    HttpOnly: true,
}

Thanks for everyone that answered

  •  Tags:  
  • go
  • Related