14
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

golangでcookieを使う

Posted at

サーバから送られてきたcookieを表示し、送られたcookieでサーバにアクセスするhttp clientのサンプルコード。

client.go
package main

import (
  "net/http"
  "fmt"
  "net/http/cookiejar"
  "net/url"
  "log"
)

func main(){
  jar, err := cookiejar.New(nil)
  if err != nil {
    log.Fatal(err)
  }
  client := &http.Client{ Jar: jar }
  res, err := client.Get("http://localhost/set_cookie")
  if err != nil {
    log.Fatal(err)
  }
  defer res.Body.Close()
  if res.StatusCode != 200 {
    fmt.Printf("StatusCode=%d\n", res.StatusCode)
    return
  }

  // Print cookie sent by server
  set_cookie_url, err := url.Parse("http://localhost/set_cookie")
  if err != nil {
    log.Fatal(err)
  }
  cookies := jar.Cookies(set_cookie_url)
  fmt.Printf("%v\n", cookies)

  // Access different url to check if cookie is sent 
  res, err = client.Get("http://localhost/dump_cookie")
  if err != nil {
    log.Fatal(err)
  }
  if res.StatusCode != 200 {
    fmt.Printf("StatusCode=%d\n", res.StatusCode)
    return
  }
}

上記のサンプルコードからのリクエストに対して、set-cookieヘッダー付きのレスポンスを送るサーバ側のサンプルコード。

server.go
package main

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

func setCookieHandler(w http.ResponseWriter, r *http.Request){
  http.SetCookie(w, &http.Cookie{
    Name: "cookie_field",
    Value: "cookie_value",
    Path: "/",
  })
  http.SetCookie(w, &http.Cookie{
    Name: "cookie_field2",
    Value: "cookie_value2",
    Path: "/",
  })
  w.WriteHeader(http.StatusOK)
}

func dumpCookieHandler(w http.ResponseWriter, r *http.Request){
  for k, v := range r.Header {
    fmt.Printf("%s:%s\n", k, v)
  }
  w.WriteHeader(http.StatusOK)
}

func main(){
  http.HandleFunc("/set_cookie", setCookieHandler)
  http.HandleFunc("/dump_cookie", dumpCookieHandler)
  log.Fatal(http.ListenAndServe(":80", nil))
}

14
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?