development-ib-fork/web/08/eigene_loesungen/Aufgabe_02/Aufgabe_02.go

50 lines
1.1 KiB
Go

package main
import (
"net/http"
"github.com/google/uuid"
)
type createHandler int
type showHandler int
type deleteHandler int
func (a createHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
uuid := uuid.New().String()
cookie := &http.Cookie{Name: "keks", Value: uuid}
http.SetCookie(w, cookie)
w.Write([]byte("Cookie erstellt!"))
}
func (b showHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("keks")
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.Write([]byte("Keks Wert: " + cookie.Value))
}
func (b deleteHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("keks")
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
cookie.MaxAge = -1
http.SetCookie(w, cookie)
w.Write([]byte("Keks gelöscht"))
}
func main() {
var a createHandler
var b showHandler
var c deleteHandler
mux := http.NewServeMux()
mux.Handle("/create-cookie", a)
mux.Handle("/show-cookie", b)
mux.Handle("/delete-cookie", c)
http.ListenAndServe("localhost:8080", mux)
}