forked from daichirata/gcsproxy
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
143 lines (126 loc) · 3.19 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
package main
import (
"context"
"flag"
"io"
"log"
"net/http"
"strconv"
"time"
"cloud.google.com/go/storage"
"github.com/gorilla/mux"
"google.golang.org/api/option"
)
var (
bind = flag.String("b", "127.0.0.1:8080", "Bind address")
verbose = flag.Bool("v", false, "Show access log")
credentials = flag.String("c", "", "The path to the keyfile. If not present, client will use your default application credentials.")
)
var (
client *storage.Client
ctx = context.Background()
)
func handleError(w http.ResponseWriter, err error) {
if err != nil {
if err == storage.ErrObjectNotExist {
http.Error(w, err.Error(), http.StatusNotFound)
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
}
func header(r *http.Request, key string) (string, bool) {
if r.Header == nil {
return "", false
}
if candidate := r.Header[key]; len(candidate) > 0 {
return candidate[0], true
}
return "", false
}
func setStrHeader(w http.ResponseWriter, key string, value string) {
if value != "" {
w.Header().Add(key, value)
}
}
func setIntHeader(w http.ResponseWriter, key string, value int64) {
if value > 0 {
w.Header().Add(key, strconv.FormatInt(value, 10))
}
}
func setTimeHeader(w http.ResponseWriter, key string, value time.Time) {
if !value.IsZero() {
w.Header().Add(key, value.UTC().Format(http.TimeFormat))
}
}
type wrapResponseWriter struct {
http.ResponseWriter
status int
}
func (w *wrapResponseWriter) WriteHeader(status int) {
w.ResponseWriter.WriteHeader(status)
w.status = status
}
func wrapper(fn func(w http.ResponseWriter, r *http.Request)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
proc := time.Now()
writer := &wrapResponseWriter{
ResponseWriter: w,
status: http.StatusOK,
}
fn(writer, r)
addr := r.RemoteAddr
if ip, found := header(r, "X-Forwarded-For"); found {
addr = ip
}
if *verbose {
log.Printf("[%s] %.3f %d %s %s",
addr,
time.Now().Sub(proc).Seconds(),
writer.status,
r.Method,
r.URL,
)
}
}
}
func proxy(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
obj := client.Bucket(params["bucket"]).Object(params["object"])
attr, err := obj.Attrs(ctx)
if err != nil {
handleError(w, err)
return
}
setStrHeader(w, "Content-Type", attr.ContentType)
setStrHeader(w, "Content-Language", attr.ContentLanguage)
setStrHeader(w, "Cache-Control", attr.CacheControl)
setStrHeader(w, "Content-Encoding", attr.ContentEncoding)
setStrHeader(w, "Content-Disposition", attr.ContentDisposition)
setIntHeader(w, "Content-Length", attr.Size)
objr, err := obj.NewReader(ctx)
if err != nil {
handleError(w, err)
return
}
io.Copy(w, objr)
}
func main() {
flag.Parse()
var err error
if *credentials != "" {
client, err = storage.NewClient(ctx, option.WithCredentialsFile(*credentials))
} else {
client, err = storage.NewClient(ctx)
}
if err != nil {
log.Fatalf("Failed to create client: %v", err)
}
r := mux.NewRouter()
r.HandleFunc("/{bucket:[0-9a-zA-Z-_]+}/{object:.*}", wrapper(proxy)).Methods("GET", "HEAD")
log.Printf("[service] listening on %s", *bind)
if err := http.ListenAndServe(*bind, r); err != nil {
log.Fatal(err)
}
}