Advertisement
Guest User

Website counter with cookies

a guest
May 21st, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.77 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "net/http"
  5.     "strconv"
  6.     "io"
  7.     "fmt"
  8. )
  9.  
  10. func main() {
  11.     http.HandleFunc("/", index)
  12.     http.Handle("/favicon.ico", http.NotFoundHandler())
  13.     http.ListenAndServe(":8080", nil)
  14. }
  15.  
  16. func index(w http.ResponseWriter, r *http.Request) {
  17.     count, err := r.Cookie("count")
  18.     var currentCount int
  19.     if err != nil {
  20.         // Cookie doesn't exist
  21.         currentCount = 1
  22.         http.SetCookie(w, &http.Cookie{
  23.             Name: "count",
  24.             Value: strconv.Itoa(currentCount),
  25.         })
  26.     } else {
  27.         currentCount, err = strconv.Atoi(count.Value)
  28.  
  29.         // Not convertable to string
  30.         if err != nil {
  31.             currentCount = 1
  32.         } else {
  33.             currentCount++
  34.         }
  35.  
  36.         count.Value = strconv.Itoa(currentCount)
  37.     }
  38.  
  39.     io.WriteString(w, fmt.Sprintf("Your current visit count is %d", currentCount))
  40.  
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement