Unique IDの生成【Go】
サードパーティのパッケージを使用します。
GitHub - satori/go.uuid: UUID package for Go
func main() { http.HandleFunc("/", index) http.HandleFunc("/read", read) http.Handle("/favicon.ico", http.NotFoundHandler()) http.ListenAndServe(":8080", nil) } func index(w http.ResponseWriter, req *http.Request) { id, err := uuid.NewV4() // unique idを生成 if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } http.SetCookie(w, &http.Cookie{ Name: "session", Value: id.String(), Path: "/read", HttpOnly: true, }) http.Redirect(w, req, "/read", http.StatusSeeOther) // Cookieをセットしたらreadにリダイレクト } func read(w http.ResponseWriter, req *http.Request) { c, err := req.Cookie("session") if err == http.ErrNoCookie { http.Error(w, err.Error(), http.StatusBadRequest) } fmt.Fprintln(w, c) }