forked from hauke96/tiny-http-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
108 lines (84 loc) · 1.99 KB
/
Copy pathmain.go
File metadata and controls
108 lines (84 loc) · 1.99 KB
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
package main
import (
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/hauke96/sigolo"
)
const configPath = "./tiny.json"
var config *Config
var cache *Cache
var client *http.Client
func main() {
prepare()
sigolo.Info("Ready to serve")
server := &http.Server{
Addr: ":" + config.Port,
WriteTimeout: 30 * time.Second,
ReadTimeout: 30 * time.Second,
Handler: http.HandlerFunc(handleGet),
}
err := server.ListenAndServe()
if err != nil {
sigolo.Fatal(err.Error())
}
}
func configureLogging() {
sigolo.FormatFunctions[sigolo.LOG_INFO] = sigolo.LogPlain
//sigolo.LogLevel = sigolo.LOG_DEBUG
}
func prepare() {
var err error
sigolo.Info("Load config")
config, err = LoadConfig(configPath)
if err != nil {
sigolo.Fatal("Could not read config: '%s'", err.Error())
}
sigolo.Info("Init cache")
cache, err = CreateCache(config.CacheFolder)
if err != nil {
sigolo.Fatal("Could not init cache: '%s'", err.Error())
}
client = &http.Client{
Timeout: time.Second * 30,
}
}
func handleGet(w http.ResponseWriter, r *http.Request) {
fullUrl := r.URL.Path + "?" + r.URL.RawQuery
sigolo.Info("Requested '%s'", fullUrl)
// Only pass request to target host when cache does not has an entry for the
// given URL.
if cache.has(fullUrl) {
content, err := cache.get(fullUrl)
if err != nil {
handleError(err, w)
} else {
w.Write(content)
}
} else {
response, err := client.Get(config.Target + fullUrl)
if err != nil {
handleError(err, w)
return
}
body, err := ioutil.ReadAll(response.Body)
response.Body.Close()
if err != nil {
handleError(err, w)
return
}
err = cache.put(fullUrl, body)
// Do not fail. Even if the put failed, the end user would be sad if he
// gets an error, even if the proxy alone works.
if err != nil {
sigolo.Error("Could not write into cache: %s", err)
}
w.Write(body)
}
}
func handleError(err error, w http.ResponseWriter) {
sigolo.Error(err.Error())
w.WriteHeader(500)
fmt.Fprintf(w, err.Error())
}