9951 explained code solutions for 126 technologies


golangHow to set cookie for HTTP request


package main

import ("net/http"; "os"; "io")

func main() {
  client := &http.Client{}
  req, _ := http.NewRequest("GET", "https://echoof.me", nil)
  req.AddCookie(&http.Cookie{
    Name: "mycookie", Value: "hi", MaxAge: 60,
  })
  r, _ := client.Do(req)
  defer r.Body.Close()
  io.Copy(os.Stdout, r.Body)
}ctrl + c
package main

default package declaration

net/http

http package to work with http protocol

http.Client{}

creates new HTTP client object

http.NewRequest

creates HTTP request object

.AddCookie(

adds given cookie to request

http.Cookie

cookie object with params

.Do(

sends given request

io.Copy(os.Stdout, r.Body)

output response body to stdout