Skip to content

Instantly share code, notes, and snippets.

@sekky0905
Last active March 20, 2017 03:59
Show Gist options
  • Save sekky0905/aecd521b05652ea5b2b29a93db1fe11a to your computer and use it in GitHub Desktop.
Save sekky0905/aecd521b05652ea5b2b29a93db1fe11a to your computer and use it in GitHub Desktop.
Go言語でCookieを操作する(設定と取得) ref: http://qiita.com/Sekky0905/items/f4cad4cacf5872df001e
// 1
cookie := &http.Cookie{
Name: "hoge", // ここにcookieの名前を記述
Value: "bar", // ここにcookieの値を記述
}
// 2
http.SetCookie(w, cookie)
type Cookie struct {
Name string
Value string
Path string // optional
Domain string // optional
Expires time.Time // optional
RawExpires string // for reading cookies only
// MaxAge=0 means no 'Max-Age' attribute specified.
// MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'
// MaxAge>0 means Max-Age attribute present and given in seconds
MaxAge int
Secure bool
HttpOnly bool
Raw string
Unparsed []string // Raw text of unparsed attribute-value pairs
}
// 1
cookie, err := r.Cookie("hoge")
if err != nil {
log.Fatal("Cookie: ", err)
}
// 2
v := cookie.Value
fmt.Println(v)
package main
import (
"net/http"
"fmt"
"log"
"html/template"
)
// cookieの設定を行う
func setCookies(w http.ResponseWriter, r *http.Request) {
cookie := &http.Cookie{
Name: "hoge",
Value: "bar",
}
http.SetCookie(w, cookie)
fmt.Fprintf(w, "Cookieの設定ができたよ")
}
// cookieの取得を行い、htmlを返す
func showCookie(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("hoge")
if err != nil {
log.Fatal("Cookie: ", err)
}
tmpl := template.Must(template.ParseFiles("./cookie.html"))
tmpl.Execute(w, cookie)
}
// メイン
func main() {
http.HandleFunc("/", setCookies)
http.HandleFunc("/cookie", showCookie)
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment