forked from harbur/docker-multi-tenancy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
83 lines (57 loc) · 1.57 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
package main
import (
"net/http"
"errors"
"io/ioutil"
"log"
)
const userAgent = "docker-multi-tenancy"
const logResponse bool = true
var (
// ErrInvalidEndpoint is returned when the endpoint is not a valid HTTP URL.
ErrInvalidEndpoint = errors.New("invalid endpoint")
ErrConnectionRefused = errors.New("Connection refused")
)
var (
localAddrString = ":9000"
unixDockerSocket = "unix:///var/run/docker.sock"
)
func dockerRequestHandler(ts *Transformers) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
var trans *Transformer
log.Println("Recieved methos ", r.Method, " path", r.URL.Path)
c, err := NewClient(unixDockerSocket)
if err != nil {
w.Write([]byte("Error"))
return
}
for _, t := range ts.transformers{
m := t.regexp.FindStringSubmatch(r.URL.Path)
if m != nil {
trans = t
break
}else{
log.Printf("Transformer %v did not math to path %v\n", t.regexp, r.URL.Path)
}
}
if trans != nil {
log.Println("Applying transformation to request")
trans.transformer.transformRequest(r)
}
resp, err := c.do( r.Method, r.URL.String(), r.Body)
if trans != nil && err == nil {
log.Println("Applying transformation to response")
trans.transformer.transformResponse(resp)
}
if resp != nil {
defer resp.Body.Close()
content, _ := ioutil.ReadAll(resp.Body)
w.Write(content)
}
}
return http.HandlerFunc(fn)
}
func main(){
log.Println("Starting multi-tenancy proxy listening at: ", localAddrString)
http.ListenAndServe(localAddrString, dockerRequestHandler(DockerTransformers))
}