main.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. // Create new or load saved session
  10. var sess *session.Session
  11. var err error
  12. sess, err = session.New(w, r, "./tmp")
  13. if err != nil {
  14. fmt.Printf("%s\n", err.Error())
  15. }
  16. defer sess.Close()
  17. if r.URL.Path == "/" {
  18. var counter int
  19. // Get value or set default
  20. if sess.IsSetInt("counter") {
  21. counter = sess.GetInt("counter", 0)
  22. } else {
  23. counter = 0
  24. }
  25. // Increment value
  26. counter++
  27. // Update
  28. sess.SetInt("counter", counter)
  29. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  30. w.Header().Set("Content-Type", "text/html")
  31. if _, err := w.Write([]byte(`
  32. <div>Hello World!</div>
  33. <div>Counter: ` + fmt.Sprintf("%d", counter) + `</div>
  34. `)); err != nil {
  35. fmt.Printf("%s\n", err.Error())
  36. }
  37. } else {
  38. w.WriteHeader(http.StatusNotFound)
  39. if _, err := w.Write([]byte(`<div>Error 404!</div>`)); err != nil {
  40. fmt.Printf("%s\n", err.Error())
  41. }
  42. }
  43. })
  44. // Delete expired session files
  45. if err := session.Clean("./tmp"); err != nil {
  46. fmt.Printf("%s\n", err.Error())
  47. }
  48. if err := http.ListenAndServe(":8080", nil); err != nil {
  49. fmt.Printf("%s\n", err.Error())
  50. }
  51. }