main.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. "github.com/vladimirok5959/golang-server-sessions/session"
  6. )
  7. func main() {
  8. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  9. // Init session
  10. sess := session.New(w, r, "./tmp")
  11. defer sess.Close()
  12. if r.URL.Path == "/" {
  13. var counter int
  14. // Get value or set default
  15. if sess.IsSetInt("counter") {
  16. counter = sess.GetInt("counter", 0)
  17. } else {
  18. counter = 0
  19. }
  20. // Increment value
  21. counter++
  22. // Update
  23. sess.SetInt("counter", counter)
  24. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  25. w.Header().Set("Content-Type", "text/html")
  26. if _, err := w.Write([]byte(`
  27. <div>Hello World!</div>
  28. <div>Counter: ` + fmt.Sprintf("%d", counter) + `</div>
  29. `)); err != nil {
  30. fmt.Printf("%s\n", err.Error())
  31. }
  32. } else {
  33. w.WriteHeader(http.StatusNotFound)
  34. if _, err := w.Write([]byte(`<div>Error 404!</div>`)); err != nil {
  35. fmt.Printf("%s\n", err.Error())
  36. }
  37. }
  38. })
  39. // Delete expired session files
  40. if err := session.Clean("./tmp"); err != nil {
  41. fmt.Printf("%s\n", err.Error())
  42. }
  43. if err := http.ListenAndServe(":8080", nil); err != nil {
  44. fmt.Printf("%s\n", err.Error())
  45. }
  46. }