fasthttp

Unable to set cookie for golang's fasthttp framework


I trying to set the cookie from the server using fasthttp framework. But the cookie value is not set properly in the response header. I don't know what I have missed in the below snippet.

package main

import (
    "log"

    "github.com/valyala/fasthttp"
)

func main() {
    if err := fasthttp.ListenAndServe(":8080", requestHandler); err != nil {
        log.Fatalf("Error in ListenAndServe: %s", err)
    }
}

func requestHandler(ctx *fasthttp.RequestCtx) {
    switch string(ctx.Path()) {
    case "/foo":
        cook1 := fasthttp.Cookie{}
        cook1.SetKey("cookie_key")
        cook1.SetValue("cookie val")
        cook1.SetMaxAge(3600000)
        cook1.SetDomain("prabhakaran.com")
        cook1.SetPath(("/"))
        cook1.SetSecure(true)
        ctx.Response.Header.Cookie(&cook1)
        ctx.SetBody([]byte("this is completely new body contents"))

    case "/bar":
        //todo: Bar handler
        // ctx.SetBody([]byte("111111111111111111111"))
    default:
        ctx.Error("Unsupported path", fasthttp.StatusNotFound)
    }
}

I tried ctx.Response.Header.SetCookie(&cook1) API too. But it won't works. Is anything missed the snippet?


Solution

  • ctx.Response.Header.Cookie(&cook1)
    

    The Cookie function is used for peek the cookie value. So, use SetCookie function instead of Cookie. If you are running the server in http protocol, remove the cook1.SetSecure(true) statement.