Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "io/ioutil"
- "log"
- "net/http"
- "os"
- "strconv"
- "sync"
- "time"
- )
- const (
- Host = ":9090"
- Timeout = time.Second * 10
- )
- type Acc struct {
- Storage map[string]int
- Mutex *sync.Mutex
- }
- var Accum Acc
- func init() {
- Accum.Storage = make(map[string]int)
- Accum.Mutex = &sync.Mutex{}
- }
- func process(w http.ResponseWriter, r *http.Request) {
- key := r.URL.Query().Get("key")
- if len(key) > 0 {
- Accum.Mutex.Lock()
- Accum.Storage[key]++
- Accum.Mutex.Unlock()
- }
- }
- func main() {
- go watcher()
- http.HandleFunc("/", process)
- log.Println("starting server on ", Host)
- err := http.ListenAndServe(Host, nil)
- if err != nil {
- log.Fatal(err)
- }
- }
- func watcher() {
- for {
- time.Sleep(Timeout)
- date := time.Now()
- Accum.Mutex.Lock()
- path := "logs/" + strconv.Itoa(date.Year()) + "/" + strconv.Itoa(int(date.Month())) + "/" + strconv.Itoa(date.Day())
- os.MkdirAll(path, os.ModePerm)
- for key, value := range Accum.Storage {
- log.Println("write", key, value)
- if value < 1 {
- continue
- }
- var current int
- file, err := ioutil.ReadFile(path + "/" + key)
- if err != nil {
- current = 0
- } else {
- current, err = strconv.Atoi(string(file))
- if err != nil {
- current = 0
- }
- }
- result := []byte(strconv.Itoa(current + value))
- ioutil.WriteFile(path+"/"+key, result, 0600)
- }
- Accum.Storage = make(map[string]int)
- Accum.Mutex.Unlock()
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement