cookies.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. "time"
  6. )
  7. func mainPage(w http.ResponseWriter, r *http.Request) {
  8. session, err := r.Cookie("session_id")
  9. loggedIn := (err != http.ErrNoCookie)
  10. if loggedIn {
  11. fmt.Fprintln(w, `<a href="/logout">logout</a>`)
  12. fmt.Fprintln(w, "Welcome, "+session.Value)
  13. } else {
  14. fmt.Fprintln(w, `<a href="/login">login</a>`)
  15. fmt.Fprintln(w, "You need to login")
  16. }
  17. }
  18. func loginPage(w http.ResponseWriter, r *http.Request) {
  19. expiration := time.Now().Add(10 * time.Hour)
  20. cookie := http.Cookie{
  21. Name: "session_id",
  22. Value: "rvasily",
  23. Expires: expiration,
  24. }
  25. http.SetCookie(w, &cookie)
  26. http.Redirect(w, r, "/", http.StatusFound)
  27. }
  28. func logoutPage(w http.ResponseWriter, r *http.Request) {
  29. session, err := r.Cookie("session_id")
  30. if err == http.ErrNoCookie {
  31. http.Redirect(w, r, "/", http.StatusFound)
  32. return
  33. }
  34. session.Expires = time.Now().AddDate(0, 0, -1)
  35. http.SetCookie(w, session)
  36. http.Redirect(w, r, "/", http.StatusFound)
  37. }
  38. func main() {
  39. http.HandleFunc("/login", loginPage)
  40. http.HandleFunc("/logout", logoutPage)
  41. http.HandleFunc("/", mainPage)
  42. fmt.Println("starting server at :8080")
  43. http.ListenAndServe(":8080", nil)
  44. }