-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_server.go
75 lines (66 loc) · 1.64 KB
/
http_server.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
package main
import (
"fmt"
"log"
"strconv"
"strings"
"time"
"github.com/garyburd/redigo/redis"
"github.com/valyala/fasthttp"
)
var pools map[int64]*redis.Pool
func newPool(server string, connections int) *redis.Pool {
return &redis.Pool{
MaxIdle: connections,
MaxActive: connections,
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", server)
if err != nil {
return nil, err
}
// if _, err := c.Do("AUTH", password); err != nil {
// c.Close()
// return nil, err
// }
return c, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
if time.Since(t) < time.Minute {
return nil
}
_, err := c.Do("PING")
return err
},
}
}
func startHTTPServer(redisServer string, connections int, httpPort int) {
pool := newPool(redisServer, connections)
pools[int64(httpPort)] = pool
if err := fasthttp.ListenAndServe(":"+strconv.Itoa(httpPort), requestHandler); err != nil {
log.Fatalf("Error in ListenAndServe: %s", err)
}
}
func requestHandler(ctx *fasthttp.RequestCtx) {
addressParts := strings.Split(ctx.LocalAddr().String(), ":")
port, _ := strconv.ParseInt(addressParts[1], 10, 32)
pool := pools[port]
conn := pool.Get()
key := ctx.Request.Header.Peek("key")
value := ctx.Request.Header.Peek("value")
// _, err := conn.Send("SET", key, value)
err := conn.Send("SET", key, value)
if err != nil {
ctx.Response.SetStatusCode(500)
fmt.Println(err)
} else {
ctx.Response.SetStatusCode(200)
}
if ctx.ConnRequestNum()%uint64(*pipelined) == 0 {
conn.Flush()
for i := 0; i < int(*pipelined); i++ {
conn.Receive()
}
}
conn.Close()
}