User985614
User985614

Reputation: 380

Unable to set Cookie using go lang

I tried looking at videos such this one and this link. A very similar question here

I tried my code as below:

func articlesHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Access-Control-Allow-Origin", "*")
    w.Header().Set("Access-Control-Allow-Headers", "Content-Type,access-control-allow-origin, access-control-allow-headers")
    // var cookie, err = r.Cookie("session_id")
    // // cookie not set
    // if err != nil {
    expiration := time.Now().Add(365 * 24 * time.Hour)
    cookie := &http.Cookie{Name: "session_id", Value: "123123", Expires: expiration}
    http.SetCookie(w, cookie)
    // }
    if r.Method == http.MethodGet {
        articles := Articles{
            Article{Title: "Title 1", Desc: "Desc 1"},
            Article{Title: "Title 2", Desc: "Desc 2"},
        }
        query := r.URL.Query()
        fmt.Println("All Article ENdpoint Hit with ", query.Get("id"))
        json.NewEncoder(w).Encode(articles)
    }
    if r.Method == http.MethodPost {
        formData := r.FormValue
        fmt.Println("Post call ", formData("id"))
        json.NewEncoder(w).Encode("Success")
    }
}

I can see in Response Header

enter image description here

But still I cant see it in my Dev Tool ---> Application

enter image description here

Because of this, My server is not able to detect the existing cookie value. Please help

Upvotes: 1

Views: 1378

Answers (1)

Shashank Vivek
Shashank Vivek

Reputation: 17514

If you are using Angular then there is an option to create a proxy and overcome the issue which @Adrian is talking about.

  1. Create a proxy.conf.json on the same level as package.json. Add below entry:
{
    "/articles": {
      "target": "http://127.0.0.1:8080",
      "secure": false
    }
}
  1. Now, make changes in angular side to call endpoints as
this.httpClient.get('/articles');
  1. Do either

ng serve --proxy-config proxy.conf.json

or update package.json with below entry:

 "scripts": {
    "start": "ng serve --proxy-config proxy.conf.json",

and do:

npm start

and use http://127.0.0.1:4200/ not http://localhost:4200

Upvotes: 1

Related Questions