-
Notifications
You must be signed in to change notification settings - Fork 50
/
main.go
68 lines (57 loc) · 1.29 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
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
)
func main() {
initServer()
log.Fatal(http.ListenAndServe(":8080", nil))
}
func initServer() {
http.HandleFunc("/proxy", ProxyRequest)
}
func ProxyRequest(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Print(err)
w.Write([]byte("{\"status\": \"error\"}"))
return
}
if err := BackendPost(string(body)); err != nil {
log.Print(err)
w.Write([]byte("{\"status\": \"error\"}"))
return
}
w.Header().Add("Content-Type", "application/json")
w.Write([]byte("{\"status\": \"ok\"}"))
}
type BackendParams struct {
ClientCode string `json:"client_code"`
OriginRequest struct {
Body string `json:"body"`
} `json:"origin_request"`
}
func BackendPost(originBody string) error {
params := BackendParams{
ClientCode: "proxy",
}
params.OriginRequest.Body = originBody
jsonParams, err := json.Marshal(params)
if err != nil {
return err
}
url := fmt.Sprintf("http://%s/process", os.Getenv("BACKEND_ADDR"))
res, err := http.Post(url, "application/json", bytes.NewReader(jsonParams))
if err != nil {
return err
}
if res.StatusCode != http.StatusOK {
return fmt.Errorf("backend response status code %d", res.StatusCode)
}
return nil
}