Advertisement
Guest User

Untitled

a guest
Jul 9th, 2018
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.49 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "io/ioutil"
  5.     "log"
  6.     "net/http"
  7.     "os"
  8.     "strconv"
  9.     "sync"
  10.     "time"
  11. )
  12.  
  13. const (
  14.     Host    = ":9090"
  15.     Timeout = time.Second * 10
  16. )
  17.  
  18. type Acc struct {
  19.     Storage map[string]int
  20.     Mutex   *sync.Mutex
  21. }
  22.  
  23. var Accum Acc
  24.  
  25. func init() {
  26.     Accum.Storage = make(map[string]int)
  27.     Accum.Mutex = &sync.Mutex{}
  28. }
  29.  
  30. func process(w http.ResponseWriter, r *http.Request) {
  31.  
  32.     key := r.URL.Query().Get("key")
  33.  
  34.     if len(key) > 0 {
  35.         Accum.Mutex.Lock()
  36.         Accum.Storage[key]++
  37.         Accum.Mutex.Unlock()
  38.     }
  39. }
  40.  
  41. func main() {
  42.  
  43.     go watcher()
  44.  
  45.     http.HandleFunc("/", process)
  46.  
  47.     log.Println("starting server on ", Host)
  48.  
  49.     err := http.ListenAndServe(Host, nil)
  50.     if err != nil {
  51.         log.Fatal(err)
  52.     }
  53.  
  54. }
  55.  
  56. func watcher() {
  57.     for {
  58.         time.Sleep(Timeout)
  59.  
  60.         date := time.Now()
  61.  
  62.         Accum.Mutex.Lock()
  63.  
  64.         path := "logs/" + strconv.Itoa(date.Year()) + "/" + strconv.Itoa(int(date.Month())) + "/" + strconv.Itoa(date.Day())
  65.  
  66.         os.MkdirAll(path, os.ModePerm)
  67.  
  68.         for key, value := range Accum.Storage {
  69.             log.Println("write", key, value)
  70.  
  71.             if value < 1 {
  72.                 continue
  73.             }
  74.  
  75.             var current int
  76.  
  77.             file, err := ioutil.ReadFile(path + "/" + key)
  78.             if err != nil {
  79.                 current = 0
  80.             } else {
  81.                 current, err = strconv.Atoi(string(file))
  82.                 if err != nil {
  83.                     current = 0
  84.                 }
  85.             }
  86.  
  87.             result := []byte(strconv.Itoa(current + value))
  88.             ioutil.WriteFile(path+"/"+key, result, 0600)
  89.         }
  90.  
  91.         Accum.Storage = make(map[string]int)
  92.  
  93.         Accum.Mutex.Unlock()
  94.  
  95.     }
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement