This repository has been archived by the owner on May 17, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
89 lines (72 loc) · 1.71 KB
/
app.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package main
import (
"bytes"
"fmt"
"log"
"os"
"strconv"
"time"
"github.com/bradfitz/gomemcache/memcache"
"github.com/google/uuid"
"github.com/valyala/fasthttp"
)
const DefaultTimeout = 10 * time.Second
func main() {
p := os.Getenv("PORT")
name := os.Getenv("NAME")
sock := os.Getenv("SOCK_PATH")
if p == "" || name == "" {
log.Fatal("missing environment")
}
mc := memcache.New(sock)
mc.Timeout = DefaultTimeout
m := func(ctx *fasthttp.RequestCtx) {
switch string(ctx.Path()) {
case "/inc":
incHandler(ctx, mc)
default:
ctx.Error("Unsupported path", fasthttp.StatusNotFound)
}
}
fasthttp.ListenAndServe(":"+p, m)
}
func incHandler(ctx *fasthttp.RequestCtx, mc *memcache.Client) {
uid := handleUUID(ctx)
i, err := mc.Get(uid)
if err != nil {
log.Println(err)
}
if i == nil || i.Value == nil || bytes.Equal(i.Value, []byte("")) {
i.Value = []byte("0")
}
strint := fmt.Sprintf("%s", i.Value)
ints, err := strconv.Atoi(strint)
if err != nil {
log.Println(err)
}
ints++
mc.Set(&memcache.Item{Key: uid, Value: []byte(strconv.Itoa(ints)), Expiration: 0})
if err != nil {
log.Println(err)
}
ctx.Response.Header.Add("NODE", os.Getenv("NAME"))
ctx.Response.SetBodyString(strconv.Itoa(ints))
}
func handleUUID(ctx *fasthttp.RequestCtx) string {
uid := ctx.Request.Header.Cookie("uuid")
if uid != nil {
c := &fasthttp.Cookie{}
c.SetKey("uuid")
c.SetValueBytes(uid)
c.SetExpire(time.Now().Add(86400 * time.Second * 365))
ctx.Response.Header.SetCookie(c)
return string(uid)
}
c := &fasthttp.Cookie{}
c.SetKey("uuid")
struid := uuid.New().String()
c.SetValue(struid)
c.SetExpire(time.Now().Add(86400 * time.Second * 365))
ctx.Response.Header.SetCookie(c)
return struid
}