-
Notifications
You must be signed in to change notification settings - Fork 581
/
main.go
177 lines (155 loc) · 5 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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
/*
Copyright 2021 The Knative Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"strconv"
"github.com/cloudevents/sdk-go/observability/opencensus/v2/client"
cloudevents "github.com/cloudevents/sdk-go/v2"
cehttp "github.com/cloudevents/sdk-go/v2/protocol/http"
"go.uber.org/zap"
"knative.dev/pkg/tracing"
"knative.dev/pkg/tracing/config"
)
/*
Example Output:
☁️ cloudevents.Event
Validation: valid
Context Attributes,
specversion: 1.0
type: dev.knative.eventing.samples.heartbeat
source: https://knative.dev/eventing-contrib/cmd/heartbeats/#event-test/mypod
id: 2b72d7bf-c38f-4a98-a433-608fbcdd2596
time: 2019-10-18T15:23:20.809775386Z
contenttype: application/json
Extensions,
beats: true
heart: yes
the: 42
Data,
{
"id": 2,
"label": ""
}
*/
// display prints the given Event in a human-readable format.
func display(event cloudevents.Event) {
fmt.Printf("☁️ cloudevents.Event\n%s", event)
}
func main() {
run(context.Background())
}
func run(ctx context.Context) {
requestLoggingEnabled, _ := strconv.ParseBool(os.Getenv("REQUEST_LOGGING_ENABLED"))
if requestLoggingEnabled {
log.Println("Request logging enabled, request logging is not recommended for production since it might log sensitive information")
}
c, err := client.NewClientHTTP(
[]cehttp.Option{
cehttp.WithMiddleware(healthzMiddleware),
cehttp.WithMiddleware(requestLoggingMiddleware(requestLoggingEnabled)),
}, nil,
)
if err != nil {
log.Fatal("Failed to create client: ", err)
}
conf, err := config.JSONToTracingConfig(os.Getenv("K_CONFIG_TRACING"))
if err != nil {
log.Printf("Failed to read tracing config, using the no-op default: %v", err)
}
tracer, err := tracing.SetupPublishingWithStaticConfig(zap.L().Sugar(), "", conf)
if err != nil {
log.Fatalf("Failed to initialize tracing: %v", err)
}
defer tracer.Shutdown(context.Background())
if err := c.StartReceiver(ctx, display); err != nil {
log.Fatal("Error during receiver's runtime: ", err)
}
}
// HTTP path of the health endpoint used for probing the service.
const healthzPath = "/healthz"
// healthzMiddleware is a cehttp.Middleware which exposes a health endpoint.
func healthzMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
if req.RequestURI == healthzPath {
w.WriteHeader(http.StatusNoContent)
} else {
next.ServeHTTP(w, req)
}
})
}
// requestLoggingMiddleware is a cehttp.Middleware which logs incoming requests.
func requestLoggingMiddleware(enabled bool) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
if enabled {
logRequest(req)
}
next.ServeHTTP(w, req)
})
}
}
type LoggableRequest struct {
Method string `json:"method,omitempty"`
URL *url.URL `json:"URL,omitempty"`
Proto string `json:"proto,omitempty"`
ProtoMajor int `json:"protoMajor,omitempty"`
ProtoMinor int `json:"protoMinor,omitempty"`
Header http.Header `json:"headers,omitempty"`
Body string `json:"body,omitempty"`
ContentLength int64 `json:"contentLength,omitempty"`
TransferEncoding []string `json:"transferEncoding,omitempty"`
Host string `json:"host,omitempty"`
Trailer http.Header `json:"trailer,omitempty"`
RemoteAddr string `json:"remoteAddr"`
RequestURI string `json:"requestURI"`
}
func logRequest(req *http.Request) {
b, err := json.MarshalIndent(toReq(req), "", " ")
if err != nil {
log.Println("failed to marshal request", err)
}
log.Println(string(b))
}
func toReq(req *http.Request) LoggableRequest {
body, err := io.ReadAll(req.Body)
if err != nil {
log.Println("failed to read request body")
}
_ = req.Body.Close()
// Replace the body with a new reader after reading from the original
req.Body = io.NopCloser(bytes.NewBuffer(body))
return LoggableRequest{
Method: req.Method,
URL: req.URL,
Proto: req.Proto,
ProtoMajor: req.ProtoMajor,
ProtoMinor: req.ProtoMinor,
Header: req.Header,
Body: string(body),
ContentLength: req.ContentLength,
TransferEncoding: req.TransferEncoding,
Host: req.Host,
Trailer: req.Trailer,
RemoteAddr: req.RemoteAddr,
RequestURI: req.RequestURI,
}
}