0

I need to pass csrf cookies _gorila_csrf and csrf_token from my HEAD-Request to my POST-Request. What is the best practice for that? For now I get the Cookie Value with res.Cookies() for the two cookies, built the Cookie-Header Value and pass to the next function. Is there any method to pass the real cookie to the next request?

var c = resp.Cookies()[0].Name+"="+resp.Cookies()[0].Value+";"+resp.Cookies()[1].Name+"="+resp.Cookies()[1].Value
var t = resp.Cookies()[1].Value

Is it possible to address the cookie by name in case more cookies are added in the future and the order changes?

Edit - Example (not working because the api url does not response with the right cookies):

package main

import (
    "fmt"
    "net/http"
    "time"
)

const url = "https://google.com"

func main() {
    client := &http.Client{
        Timeout: time.Second * 5,
    }
    r, _ := http.NewRequest("HEAD", url, nil)
    resp, _ := client.Do(r)

    var c = resp.Cookies()[0].Name + "=" + resp.Cookies()[0].Value + ";" + resp.Cookies()[1].Name + "=" + resp.Cookies()[1].Value
    var t = resp.Cookies()[1].Value

    fmt.Println(c)
    fmt.Println(t)
    }
sokolata
  • 491
  • 3
  • 7
  • 21
  • What `HEAD` and `POST` requests? I'm afraid the problem isn't clear... Please post a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). Also, if the question is about Go, why tag it with [tag:django-csrf]? – jub0bs Dec 08 '22 at 23:24
  • @jub0bs I'm talking about http methods HEAD and POST. Updated my Question with example code. – sokolata Dec 09 '22 at 00:42
  • Your code snippet says nothing about any `POST` request... – jub0bs Dec 11 '22 at 16:44
  • If I correctly understand what you're trying to do, you would need to instantiate a client with a (non-`nil`) cookie jar. See https://pkg.go.dev/net/http/cookiejar – jub0bs Dec 11 '22 at 17:03
  • See https://stackoverflow.com/questions/12756782/go-http-post-and-use-cookies – jub0bs Dec 11 '22 at 17:17

0 Answers0