-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
146 lines (127 loc) · 4.18 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
144
145
146
package main
import (
"bufio"
"context"
"flag"
"fmt"
"log/slog"
"net/http"
"os"
azlog "github.com/Azure/azure-sdk-for-go/sdk/azcore/log"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
var (
listen string = "127.0.0.1:8080"
accountName string
containerName string
// logger = slog.Default() // for default (unstructured) logs
logger = slog.New(slog.NewJSONHandler(os.Stdout, nil))
)
func main() {
// parse comand line args and environment variables
flag.StringVar(&listen, "http-listen-addr", LookupEnvOrString("HTTP_LISTEN_ADDR", listen), "http service listen address")
flag.StringVar(&accountName, "account-name", LookupEnvOrString("AZURE_STORAGE_ACCOUNT", accountName), "Azure Storage account name")
flag.StringVar(&containerName, "container-name", LookupEnvOrString("AZURE_STORAGE_CONTAINER", containerName), "Azure Storage blob container name")
flag.Parse()
// check mandatory parameters
if len(accountName) == 0 {
logger.Error("storage account name not specified")
os.Exit(1)
}
if len(containerName) == 0 {
logger.Error("storage container name not specified")
os.Exit(1)
}
// print azure log output to stdout
azlog.SetListener(func(event azlog.Event, s string) {
logger.Info("azure log", "event", s)
})
// include only azidentity credential logs
azlog.SetEvents(azidentity.EventAuthentication)
// get azure credentials
// https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/azidentity
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
logger.Error("get credentials", "error", err)
os.Exit(1)
}
// set azure blob storage client
var client *azblob.Client
serviceURL := fmt.Sprintf("https://%s.blob.core.windows.net/", accountName)
os.Setenv("AZURE_STORAGE_AUTH_MODE", "login")
accountKey := LookupEnvOrString("AZURE_STORAGE_KEY", "")
if len(accountKey) != 0 {
// accountKey defined (running locally with azure-cli authentication)
// use key to authorize
key, keyerr := azblob.NewSharedKeyCredential(accountName, accountKey)
if keyerr != nil {
logger.Error("storage account key", "error", keyerr)
os.Exit(1)
}
client, err = azblob.NewClientWithSharedKeyCredential(serviceURL, key, nil)
} else {
client, err = azblob.NewClient(serviceURL, cred, nil)
}
if err != nil {
logger.Error("storage blob client", "error", err)
os.Exit(1)
}
ctx := context.Background()
// serve requests
logger.Info("serving proxy requests", "addr", listen, "storage account", accountName, "container", containerName)
http.Handle("/healthz", healthHandler(ctx))
http.Handle("/", rootHandler(ctx, client, containerName))
err = http.ListenAndServe(listen, nil)
if err != nil {
logger.Error("http listener", "error", err)
os.Exit(1)
}
} // main
func LookupEnvOrString(key string, defaultVal string) string {
if val, ok := os.LookupEnv(key); ok {
return val
}
return defaultVal
}
func rootHandler(ctx context.Context, client *azblob.Client, containerName string) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
key := r.URL.Path
if key[0] == '/' {
key = key[1:]
}
blobFullName := fmt.Sprintf("%s/%s", containerName, key)
if r.Method == "GET" {
streamResponse, err := client.DownloadStream(ctx, containerName, key, &azblob.DownloadStreamOptions{})
if err != nil {
logger.Error("download blob", "blob", blobFullName, "error", err)
w.WriteHeader(http.StatusNotFound)
return
}
logger.Info("proxying", "blob", blobFullName)
bufferedReader := bufio.NewReader(streamResponse.Body)
_, err = bufferedReader.WriteTo(w)
if err != nil {
logger.Error("failed to proxy", "blob", blobFullName, "error", err)
}
} else {
logger.Error("wrong method", "method", r.Method, "blob", blobFullName)
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
}
return http.HandlerFunc(fn)
}
func healthHandler(ctx context.Context) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
w.WriteHeader(http.StatusOK)
return
} else {
logger.Error("wrong method", "method", r.Method, "path", r.URL.Path)
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
}
return http.HandlerFunc(fn)
}