I defined two handler functions, setCookie and getCookie. The first function, setCookie, is called by getting access to localhost:8080/set_cookie, and then sends a HTTP response including two cookies. The other function, getCookie, is called by accessing to localhost:8080/get_cookie, and then gets Cookie object. I expect getCookie function to show information about two cookies, but a message, "first_cookie is not set successfully", is shown on a web browser.
Do you have any idea solving this problem?
package main
import (
"fmt"
"net/http"
)
func setCookie(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "setCookie called")
c1 := http.Cookie{
Name: "first_cookie",
Value: "Go Web App",
HttpOnly: true,
}
c2 := http.Cookie{
Name: "second_cookie",
Value: "Another service",
HttpOnly: true,
}
http.SetCookie(w, &c1)
http.SetCookie(w, &c2)
}
func getCookie(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "getCookie called")
c1, err := r.Cookie("first_cookie")
if err != nil {
fmt.Fprintln(w, "first_cookie is not set successfully.")
}
ca := r.Cookies()
fmt.Fprintln(w, c1)
fmt.Fprintln(w, ca)
}
func main() {
server := http.Server{
Addr: "127.0.0.1:8080",
}
http.HandleFunc("/set_cookie", setCookie)
http.HandleFunc("/get_cookie", getCookie)
server.ListenAndServe()
}