forked from juanmanuel-tirado/savetheworldwithgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
56 lines (49 loc) · 1.19 KB
/
main.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
package main
import (
"fmt"
"net/http"
"net/http/cookiejar"
url2 "net/url"
"strconv"
)
func cookieSetter(w http.ResponseWriter, r *http.Request) {
counter, err := r.Cookie("counter")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
value, err := strconv.Atoi(counter.Value)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
value = value + 1
newCookie := http.Cookie{
Name: "counter",
Value: strconv.Itoa(value),
}
http.SetCookie(w, &newCookie)
w.WriteHeader(http.StatusOK)
}
func main() {
http.HandleFunc("/cookie", cookieSetter)
go http.ListenAndServe(":8090", nil)
jar, err := cookiejar.New(nil)
if err != nil {
panic(err)
}
cookies := []*http.Cookie{
&http.Cookie{Name:"counter",Value:"1"},
}
url := "http://localhost:8090/cookie"
u, _ := url2.Parse(url)
jar.SetCookies(u, cookies)
client := http.Client{Jar: jar}
for i:=0; i<5; i++ {
_, err := client.Get(url)
if err != nil {
panic(err)
}
fmt.Println("Client cookie",jar.Cookies(u))
}
}