-
Notifications
You must be signed in to change notification settings - Fork 13
/
main.go
108 lines (88 loc) · 2.37 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
// Copyright 2018 Google Inc. All Rights Reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package main
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
)
type CloudEvent struct {
EventType string `json:"eventType"`
EventID string `json:"eventID"`
CloudEventsVersion string `json:"cloudEventsversion"`
ContentType string `json:"contentType"`
Source string `json:"source"`
EventTime string `json:"eventTime"`
Data interface{} `json:"data"`
}
type HTTPEvent struct {
Path string `json:"path"`
Method string `json:"method"`
Headers map[string]string `json:"headers"`
Host string `json:"host"`
Query map[string]string `json:"query"`
Params map[string]string `json:"params"`
Body string `json:"body"`
}
type HTTPResponse struct {
Body string `json:"body"`
StatusCode int `json:"statusCode"`
Headers map[string]string `json:"headers,omitempty"`
}
func main() {
log.Println("Starting HTTP server...")
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
data, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Println(err)
w.WriteHeader(500)
return
}
r.Body.Close()
var ce CloudEvent
if err := json.Unmarshal(data, &ce); err != nil {
log.Println(err)
w.WriteHeader(500)
return
}
log.Printf("Handling HTTP event %s ...", ce.EventID)
e, err := httpEvent(ce.Data)
if err != nil {
log.Println(err)
w.WriteHeader(500)
return
}
headers := make(map[string]string)
headers["Compute-Type"] = "container"
response := HTTPResponse{
Body: string(e.Body),
Headers: headers,
StatusCode: 200,
}
data, err = json.MarshalIndent(&response, "", " ")
if err != nil {
log.Println(err)
w.WriteHeader(500)
return
}
w.Write(data)
})
if err := http.ListenAndServe(":80", nil); err != nil {
log.Fatal(err)
}
}
func httpEvent(v interface{}) (*HTTPEvent, error) {
data, err := json.Marshal(v)
if err != nil {
log.Println("can't marshal HTTP event")
return nil, err
}
var e HTTPEvent
if err := json.Unmarshal(data, &e); err != nil {
log.Println("can't unmarshal HTTP event")
return nil, err
}
return &e, nil
}