gohttpsessiongo-gingorilla

Gorilla session package error : "securecookie: hash key is not set"


I created an HTTP API to register with the GIN HTTP package and Gorilla Sessions. But I get an error message like the following:

"error": "securecookie: hash key is not set"

here is my code :

package main

import(
    "github.com/joho/godotenv"
    "github.com/gin-gonic/gin"
    "github.com/gorilla/sessions"
    "os"
    "my-project/database"
)

type Register struct{
    Email string 'json:"email"' 
    Password string 'json:"password"'
}

var Store = sessions.NewCookieStore([]byte(os.Getenv("SESSION_KEY")))

func Register(c *gin.Context){
    session, err := Store.Get(c.Request, "my-session")
    req := new(Register)
    err := c.ShouldBindJson(&req)
    if err != nil {
        c.Json(400, "failed to register")
        return
    }
    err = database.CreateUser(req)
    if err != nil {
        c.Json(500, "failed to create user")
        return
    }
    session.Values["email"] = req.Email
    err = session.Save(c.Request, c.Writer)
    if err != nil {
        c.Json(500, gin.H{"error":err.Error(),})
        return
    }
    c.Json(200, gin.H{
        "massage":"user created successfuly",
    })
}

func main(){
    err := godotenv.Load()
    if err != nil {
       panic(err)
    }
    r := gin.Default()
    r.Post("/register", Register)
    r.Run(":8080")
}

I want my postman to show JSON, like "User successfully created"


Solution

  • This line is getting a key from ENV variable named SESSION_KEY:

    var Store = sessions.NewCookieStore([]byte(os.Getenv("SESSION_KEY")))
    

    Most probably this variable is not set and that's why you get the error.

    If you're running the program from terminal, check if it's there:

    env | grep SESSION_KEY
    

    If nothing comes out, then it's not and you should set it:

    export SESSION_KEY="something"