-
Notifications
You must be signed in to change notification settings - Fork 67
/
main.go
150 lines (126 loc) · 3.93 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
/*
Copyright 2020 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 (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
cloudevents "github.com/cloudevents/sdk-go/v2"
"github.com/cloudevents/sdk-go/v2/binding"
cehttp "github.com/cloudevents/sdk-go/v2/protocol/http"
"github.com/kelseyhightower/envconfig"
"github.com/streadway/amqp"
"go.uber.org/zap"
"knative.dev/eventing/pkg/kncloudevents"
"knative.dev/pkg/logging"
)
const (
defaultMaxIdleConnections = 1000
defaultMaxIdleConnectionsPerHost = 1000
)
type envConfig struct {
Port int `envconfig:"PORT" default:"8080"`
BrokerURL string `envconfig:"BROKER_URL" required:"true"`
ExchangeName string `envconfig:"EXCHANGE_NAME" required:"true"`
channel *amqp.Channel
logger *zap.SugaredLogger
}
func main() {
var env envConfig
if err := envconfig.Process("", &env); err != nil {
log.Fatal("Failed to process env var", zap.Error(err))
}
conn, err := amqp.Dial(env.BrokerURL)
if err != nil {
log.Fatalf("failed to connect to RabbitMQ: %s", err)
}
defer conn.Close()
env.channel, err = conn.Channel()
if err != nil {
log.Fatalf("failed to open a channel: %s", err)
}
defer env.channel.Close()
env.logger = logging.FromContext(context.Background())
connectionArgs := kncloudevents.ConnectionArgs{
MaxIdleConns: defaultMaxIdleConnections,
MaxIdleConnsPerHost: defaultMaxIdleConnectionsPerHost,
}
kncloudevents.ConfigureConnectionArgs(&connectionArgs)
receiver := kncloudevents.NewHTTPMessageReceiver(env.Port)
if err := receiver.StartListen(context.Background(), &env); err != nil {
log.Fatalf("failed to start listen, %v", err)
}
}
func (env *envConfig) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
// validate request method
if request.Method != http.MethodPost {
env.logger.Warn("unexpected request method", zap.String("method", request.Method))
writer.WriteHeader(http.StatusMethodNotAllowed)
return
}
// validate request URI
if request.RequestURI != "/" {
writer.WriteHeader(http.StatusNotFound)
return
}
ctx := request.Context()
message := cehttp.NewMessageFromHttpRequest(request)
defer message.Finish(nil)
event, err := binding.ToEvent(ctx, message)
if err != nil {
env.logger.Warn("failed to extract event from request", zap.Error(err))
writer.WriteHeader(http.StatusBadRequest)
return
}
// run validation for the extracted event
validationErr := event.Validate()
if validationErr != nil {
env.logger.Warn("failed to validate extracted event", zap.Error(validationErr))
writer.WriteHeader(http.StatusBadRequest)
return
}
statusCode, err := env.send(event)
if err != nil {
env.logger.Error("failed to send event,", err)
}
writer.WriteHeader(statusCode)
}
func (env *envConfig) send(event *cloudevents.Event) (int, error) {
bytes, err := json.Marshal(event)
if err != nil {
return http.StatusBadRequest, fmt.Errorf("failed to marshal event, %w", err)
}
headers := amqp.Table{
"type": event.Type(),
"source": event.Source(),
"subject": event.Subject(),
}
for key, val := range event.Extensions() {
headers[key] = val
}
if err := env.channel.Publish(
env.ExchangeName,
"", // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
Headers: headers,
ContentType: "application/json",
Body: bytes,
}); err != nil {
return http.StatusInternalServerError, fmt.Errorf("failed to publish message")
}
return http.StatusAccepted, nil
}