forked from WEB-IMB-WS2526/lab-development-imb
69 lines
1.3 KiB
Go
69 lines
1.3 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
// create Cookie HTTP Handler
|
|
func createHandler(w http.ResponseWriter, r *http.Request) {
|
|
|
|
//UUID erzeugen
|
|
id := uuid.NewString()
|
|
|
|
// Keks erstellen
|
|
|
|
cookie := &http.Cookie{
|
|
Name: "keks",
|
|
Value: id,
|
|
Path: "/",
|
|
}
|
|
|
|
// keks setzten
|
|
http.SetCookie(w, cookie)
|
|
|
|
// Ausgabe Browser
|
|
fmt.Fprintf(w, "Keks erstellt: %s\n", id)
|
|
|
|
}
|
|
|
|
// show Cookie, falls vorhanden
|
|
func showHandler(w http.ResponseWriter, r *http.Request) {
|
|
cookie, err := r.Cookie("keks")
|
|
if err != nil {
|
|
fmt.Fprintln(w, "Kein Cookie vorhanden")
|
|
return
|
|
}
|
|
fmt.Fprintf(w, "Keks gefunden: %s\n", cookie.Value)
|
|
|
|
}
|
|
|
|
// delete Cookie
|
|
func deleteHandler(w http.ResponseWriter, r *http.Request) {
|
|
cookie, err := r.Cookie("keks")
|
|
if err != nil {
|
|
http.Error(w, "Kein Cookie gefunden, löschen nicht möglich", http.StatusBadRequest)
|
|
return
|
|
}
|
|
// Maxage - 1 löscht Cookie
|
|
cookie.MaxAge = -1
|
|
// schickt neuen Set Cookie Header an Browser
|
|
http.SetCookie(w, cookie)
|
|
fmt.Fprintln(w, "Cookie gelöscht")
|
|
}
|
|
|
|
func main() {
|
|
|
|
// Endpunkte registrieren
|
|
|
|
http.HandleFunc("/create-cookie", createHandler)
|
|
http.HandleFunc("/show-cookie", showHandler)
|
|
http.HandleFunc("/delete-cookie", deleteHandler)
|
|
|
|
fmt.Println("Server läuft auf http://localhost:8080")
|
|
http.ListenAndServe(":8080", nil)
|
|
|
|
}
|