-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
164 lines (125 loc) · 3.41 KB
/
main.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"strings"
"time"
"github.com/go-redis/redis"
"github.com/siddontang/go/log"
"github.com/pinpt/go-common/hash"
)
func setHeader(name string, r *http.Request) {
if obj := r.Header[name]; len(obj) > 0 {
if nameValue := obj[0]; nameValue != "" {
r.Header.Add(name, nameValue)
}
}
}
func mainHandler(w http.ResponseWriter, r *http.Request) {
redisClient := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password set
DB: 0, // use default DB
DialTimeout: 10 * time.Second,
ReadTimeout: 30 * time.Second,
WriteTimeout: 30 * time.Second,
PoolSize: 10,
PoolTimeout: 30 * time.Second,
MaxRetries: 5,
MinRetryBackoff: time.Second * 3,
MaxRetryBackoff: time.Second * 6,
})
defer redisClient.Close()
client := &http.Client{}
newURL := r.Header["X-Host"][0]
log.Info(fmt.Sprintf("url %s", newURL))
postBodyBts, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Error("Err", err)
}
r.Body.Close()
bodyReader := bytes.NewReader(postBodyBts)
r.Body = ioutil.NopCloser(bodyReader)
requestHash := hash.Values(newURL, r.Method, string(postBodyBts))
log.Info(fmt.Sprintf("hash[%s]", requestHash))
redisValue, err := redisClient.Get(requestHash).Result()
if err != nil && err != redis.Nil {
log.Error("Err", err)
panic(err)
}
var responseBytes []byte
if redisValue == "" {
newReq, err := http.NewRequest(r.Method, newURL, r.Body)
if err != nil {
log.Error("Err", err)
}
r.Header.Del("X-Host")
newReq.Header = r.Header
response, err := client.Do(newReq)
log.Info("status", response.Status)
defer func() {
err := response.Body.Close()
if err != nil {
log.Error("Err", err)
}
}()
responseBytes, err = ioutil.ReadAll(response.Body)
if err != nil {
log.Errorf("Err", err)
}
err = redisClient.Set(requestHash, string(responseBytes), 0).Err()
if err != nil {
log.Error("Err", err)
panic(err)
}
btsHeader, err := json.Marshal(response.Header)
if err != nil {
log.Error("Err", btsHeader)
}
log.Info(fmt.Sprintf("setting headers %s => %s ", requestHash, string(btsHeader)))
err = redisClient.Set(requestHash+"headers", string(btsHeader), 0).Err()
if err != nil {
log.Error("Err", err)
panic(err)
}
log.Info(fmt.Sprintf("saved key in cache [%s]", requestHash))
log.Debug(fmt.Sprintf("response => %s", string(responseBytes)))
for keyHeader, valueHeader := range response.Header {
w.Header().Set(keyHeader, strings.Join(valueHeader, ","))
}
} else {
log.Debug(fmt.Sprintf("using cache [%s] = > %s", requestHash, redisValue))
responseBytes = []byte(redisValue)
headersValue, err := redisClient.Get(requestHash + "headers").Result()
if err != nil && err != redis.Nil {
log.Error("Err", err)
panic(err)
}
var headers map[string][]string
err = json.Unmarshal([]byte(headersValue), &headers)
if err != nil {
log.Error("Err", err)
}
for keyHeader, valueHeader := range headers {
w.Header().Set(keyHeader, strings.Join(valueHeader, ","))
}
}
w.Write(responseBytes)
}
func main() {
http.HandleFunc("/", mainHandler)
if len(os.Args) > 1 {
log.SetLevelByName(os.Args[1])
} else {
log.SetLevelByName("info")
}
fmt.Println("server running")
err := http.ListenAndServe(":3645", nil)
if err != nil {
log.Error("Err", err)
}
}