-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp_proxy.go
58 lines (48 loc) · 1.18 KB
/
http_proxy.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
package main
import (
"fmt"
"io"
"net/http"
)
const (
applicationJson = "application/json"
)
type errorResponse struct {
Error string `json:"error"`
}
func proxyRequest(writer http.ResponseWriter, request *http.Request) {
if request.Method == http.MethodOptions {
setCorsHeader(writer)
writer.WriteHeader(http.StatusOK)
return
} else if request.Method != http.MethodPost {
handleProxyErr(writer, "invalid HTTP method")
return
}
body, err := io.ReadAll(request.Body)
if err != nil {
handleProxyErr(writer, err.Error())
return
}
if verbose {
fmt.Println("Got request: " + string(body))
}
res, resBody, err := nodeRequest(body)
if err != nil {
handleProxyErr(writer, err.Error())
return
}
writer.Header().Set("Content-Type", applicationJson)
setCorsHeader(writer)
writer.WriteHeader(res.StatusCode)
_, _ = writer.Write(resBody)
}
func handleProxyErr(writer http.ResponseWriter, msg string) {
writer.Header().Set("Content-Type", applicationJson)
setCorsHeader(writer)
writer.WriteHeader(http.StatusInternalServerError)
_, err := writer.Write(nodeRequestFailedFormat(msg))
if err != nil {
fmt.Println("Could not write errors response: " + err.Error())
}
}