現在、Go言語によるサーバ構築を勉強中の者です。
以下のようなコードを書き、
①localhost:8080/set_cookieにアクセス → 関数setCookieによってクッキーをブラウザに送信し、
②localhost:8080/get_cookieにアクセス → 関数getCookieによってクッキーを取得し、画面上に表示する
ような動作を期待しました。
しかし、①はうまく動作するのですが、②のところで、『クッキーが存在しませんよ』と表示され、つまづいてしまいます。
これはコードに問題があるのでしょうか?
それとも他に何か考えられる原因はありますか?
よろしくお願いします。
実行環境
Google Chrome バージョン: 65.0.3325.181
Go
1package main 2 3import ( 4 "fmt" 5 "net/http" 6) 7 8func setCookie(w http.ResponseWriter, r *http.Request) { 9 fmt.Fprintln(w, "setCookie called") 10 c1 := http.Cookie{ 11 Name: "first_cookie", 12 Value: "Go Web App", 13 HttpOnly: true, 14 } 15 c2 := http.Cookie{ 16 Name: "second_cookie", 17 Value: "Another service", 18 HttpOnly: true, 19 } 20 http.SetCookie(w, &c1) 21 http.SetCookie(w, &c2) 22} 23 24func getCookie(w http.ResponseWriter, r *http.Request) { 25 fmt.Fprintln(w, "getCookie called") 26 c1, err := r.Cookie("first_cookie") 27 if err != nil { 28 fmt.Fprintln(w, "クッキーが存在しませんよ") 29 } 30 ca := r.Cookies() 31 fmt.Fprintln(w, c1) 32 fmt.Fprintln(w, ca) 33} 34 35func main() { 36 server := http.Server{ 37 Addr: "127.0.0.1:8080", 38 } 39 http.HandleFunc("/set_cookie", setCookie) 40 http.HandleFunc("/get_cookie", getCookie) 41 server.ListenAndServe() 42} 43
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。