I am trying to set cookies from Go web server and then reading it in the chrome browser.
Here is my code
package main
import (
"fmt"
"net/http"
"time"
)
func setCookies(w http.ResponseWriter, r *http.Request){
expiration := time.Now().Add(365 * 24 * time.Hour)
c1 := http.Cookie{Name: "SpiderMan: Far from home",Value : "HollyWood", Path: "/", Expires: expiration, Secure: false}
http.SetCookie(w,&c1)
c2 := http.Cookie{Name: "Kabir Singh",Value: "BollyWood", Path: "/", Expires: expiration, Secure: false}
http.SetCookie(w,&c2)
// w.Header().Set("Set-Cookie",c1.String())
// w.Header().Add("Set-Cookie",c2.String())
// HttpOnly: true
fmt.Fprintf(w, "")
}
func getCookies(w http.ResponseWriter, r *http.Request){
// h := r.Header["Kabir Singh"]
// fmt.Fprintln(w,h)
c1, err := r.Cookie("Kabir Singh")
if err != nil {
fmt.Fprintln(w, "first_cookie is not set successfully." ,err)
}
ca := r.Cookies()
fmt.Fprintln(w, c1)
fmt.Fprintln(w, ca)
}
func main() {
server := http.Server{
Addr: "127.0.0.1:2020",
}
http.HandleFunc("/set_cookies", setCookies)
http.HandleFunc("/get_cookies", getCookies)
server.ListenAndServe()
}
After setting the cookies from call set_cookies when I am trying to get the cookies in the chrome browser I get this output:
first_cookie is not set successfully. http: named cookie not present
[]
I have read similar threads but none of it worked.