-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwebCookie.go
64 lines (53 loc) · 1.17 KB
/
webCookie.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package webServer
import (
"fmt"
"log"
"net/http"
"text/template"
)
// cookie を格納する
func setCookies(w http.ResponseWriter, r *http.Request) {
cookie01 := &http.Cookie{
Name: "hoge",
Value: "bar",
MaxAge: 30,
}
http.SetCookie(w, cookie01)
cookie02 := &http.Cookie{
Name: "hello",
Value: "world",
MaxAge: 30,
}
http.SetCookie(w, cookie02)
fmt.Fprintf(w, "Cookieの設定ができたよ")
}
// cookie を取得して テンプレートに埋め込む
func showCookie(w http.ResponseWriter, r *http.Request) {
cookie01, err := r.Cookie("hoge")
if err != nil {
log.Fatal("Cookie: ", err)
}
cookie02, err := r.Cookie("hello")
if err != nil {
log.Fatal("Cookie: ", err)
}
// すべての Cookie を取得
cookies := r.Cookies()
fmt.Println(cookies)
d := struct {
C01 *http.Cookie
C02 *http.Cookie
}{
C01: cookie01,
C02: cookie02,
}
tmpl := template.Must(template.ParseFiles("web/cookie.html"))
tmpl.Execute(w, d)
}
func MainCookie() {
http.HandleFunc("/cookie-set", setCookies)
http.HandleFunc("/cookie-get", showCookie)
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal("ListenAndServe: ", err)
}
}