-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
95 lines (80 loc) · 2.14 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
package main
import (
"encoding/base64"
"flag"
"io/ioutil"
"log"
"net/http"
"net/http/httptest"
"net/url"
"os"
"github.com/aws/aws-lambda-go/lambda"
"github.com/theaaf/image-proxy/proxy"
)
type Request struct {
Path string `json:"path"`
QueryStringParameters map[string]string `json:"queryStringParameters"`
}
type Response struct {
Headers map[string]string `json:"headers"`
StatusCode int `json:"statusCode"`
Body string `json:"body"`
IsBase64Encoded bool `json:"isBase64Encoded"`
}
func Handler(config *proxy.Configuration) func(*Request) (*Response, error) {
return func(request *Request) (*Response, error) {
requestURL, err := url.Parse(request.Path)
if err != nil {
return &Response{
StatusCode: http.StatusBadRequest,
Headers: map[string]string{
"Content-Type": "text/plain",
},
Body: err.Error(),
}, nil
}
parameters := url.Values{}
for k, v := range request.QueryStringParameters {
parameters.Add(k, v)
}
requestURL.RawQuery = parameters.Encode()
pr, err := proxy.NewRequestFromURL(requestURL)
if err != nil {
return &Response{
StatusCode: http.StatusBadRequest,
Headers: map[string]string{
"Content-Type": "text/plain",
},
Body: err.Error(),
}, nil
}
rec := httptest.NewRecorder()
proxy.Proxy(config, rec, pr)
result := rec.Result()
defer result.Body.Close()
data, _ := ioutil.ReadAll(result.Body)
headers := make(map[string]string)
for k := range result.Header {
headers[k] = result.Header.Get(k)
}
return &Response{
StatusCode: result.StatusCode,
Body: base64.StdEncoding.EncodeToString(data),
Headers: headers,
IsBase64Encoded: true,
}, nil
}
}
func main() {
flags := flag.NewFlagSet(os.Args[0], flag.ContinueOnError)
if err := flags.Parse(os.Args[1:]); err != nil {
if err == flag.ErrHelp {
// Exit with no error if --help was given. This is used to test the build.
os.Exit(0)
}
log.Fatal(err)
}
config := &proxy.Configuration{}
config.LoadEnvironmentVariables()
lambda.Start(Handler(config))
}