-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
122 lines (102 loc) · 2.58 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
package main
import (
"flag"
"fmt"
"github.com/golang/groupcache"
"github.com/gorilla/mux"
"github.com/vokalinteractive/go-loggly"
"launchpad.net/goamz/aws"
"launchpad.net/goamz/ec2"
"launchpad.net/goamz/s3"
"log"
"net/http"
"os"
"vip/fetch"
"vip/peer"
"vip/store"
)
var (
cache *groupcache.Group
peers peer.CachePool
storage store.ImageStore
authToken string
httpport *string = flag.String("httpport", "8080", "target port")
)
func listenHttp() {
log.Printf("Listening on port :%s\n", *httpport)
cert := os.Getenv("SSL_CERT")
key := os.Getenv("SSL_KEY")
port := fmt.Sprintf(":%s", *httpport)
if cert != "" && key != "" {
log.Println("Serving via SSL")
if err := http.ListenAndServeTLS(port, cert, key, nil); err != nil {
log.Fatalf("Error starting server: %s\n", err.Error())
}
} else {
if err := http.ListenAndServe(port, nil); err != nil {
log.Fatalf("Error starting server: %s\n", err.Error())
}
}
}
func getRegion() aws.Region {
region := os.Getenv("AWS_REGION")
aws_region, ok := aws.Regions[region]
if ok {
return aws_region
} else {
log.Printf(
"\"%s\" is not a valid AWS_REGION parameter provided, defaulting to us-east-1",
region)
return aws.USEast
}
}
func init() {
flag.Parse()
loggly_key := os.Getenv("LOGGLY_KEY")
if loggly_key != "" {
log.SetOutput(loggly.New(loggly_key, "vip"))
}
r := mux.NewRouter()
authToken = os.Getenv("AUTH_TOKEN")
if authToken == "" {
log.Println("No AUTH_TOKEN parameter provided, uploads are insecure")
}
r.Handle("/upload/{bucket_id}", verifyAuth(handleUpload))
r.HandleFunc("/{bucket_id}/{image_id}", handleImageRequest)
r.HandleFunc("/ping", handlePing)
http.Handle("/", r)
}
func main() {
awsAuth, err := aws.EnvAuth()
if err != nil {
log.Fatalf(err.Error())
}
s3conn := s3.New(awsAuth, getRegion())
storage = store.NewS3Store(s3conn)
if os.Getenv("DEBUG") == "True" {
peers = peer.DebugPool()
} else {
peers = peer.Pool(ec2.New(awsAuth, aws.USEast))
}
peers.SetContext(func(r *http.Request) groupcache.Context {
return fetch.RequestContext(r)
})
cache = groupcache.NewGroup("ImageProxyCache", 64<<20, groupcache.GetterFunc(
func(c groupcache.Context, key string, dest groupcache.Sink) error {
log.Printf("Cache MISS for key -> %s", key)
// Get image data from S3
b, err := fetch.ImageData(storage, c)
if err != nil {
return err
}
return dest.SetBytes(b)
}))
go peers.Listen()
go listenHttp()
log.Println("Cache listening on port :" + peers.Port())
s := &http.Server{
Addr: ":" + peers.Port(),
Handler: peers,
}
s.ListenAndServe()
}