-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
81 lines (69 loc) · 1.61 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
package main
import (
"context"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/samber/lo"
)
func getEnv(key string, fallback ...string) string {
value := os.Getenv(key)
if len(value) == 0 {
if len(fallback) > 0 {
return fallback[0]
}
panic(fmt.Errorf("var not found: %s", key))
}
return value
}
type Proxy struct {
S3Client *s3.Client
Bucket string
}
func (p Proxy) Handle(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
obj, err := p.S3Client.GetObject(r.Context(), &s3.GetObjectInput{
Bucket: &p.Bucket,
Key: &r.URL.Path,
})
if err != nil {
var nsk *types.NoSuchKey
if errors.As(err, &nsk) {
w.WriteHeader(http.StatusNotFound)
return
}
panic(err)
}
defer obj.Body.Close()
w.Header().Add("Content-Length", fmt.Sprintf("%d", *obj.ContentLength))
io.Copy(w, obj.Body)
}
func main() {
bucket := getEnv("BUCKET")
endpoint := getEnv("ENDPOINT")
forcePathStype := getEnv("FORCE_PATH_STYLE") != ""
disableHTTPS := getEnv("DISABLE_HTTPS", "0") != "0"
cfg := lo.Must(config.LoadDefaultConfig(context.Background()))
if endpoint != "" {
cfg.BaseEndpoint = &endpoint
}
proxy := Proxy{
Bucket: bucket,
S3Client: s3.NewFromConfig(cfg, func(o *s3.Options) {
o.UsePathStyle = forcePathStype
o.EndpointOptions.DisableHTTPS = disableHTTPS
}),
}
http.HandleFunc("/*", proxy.Handle)
log.Fatal(http.ListenAndServe(":9292", nil))
}