This repository was archived by the owner on Jun 11, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
219 lines (187 loc) · 5.5 KB
/
main.go
File metadata and controls
219 lines (187 loc) · 5.5 KB
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
// Copyright 2020 Opsani
//
// 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 (
"crypto/tls"
"fmt"
"log"
"math"
"net/http"
"net/url"
"os"
"strconv"
"sync"
"time"
"github.com/ansrivas/fiberprometheus/v2"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/logger"
"github.com/gofiber/fiber/v2/middleware/requestid"
"github.com/inhies/go-bytesize"
"github.com/valyala/fasthttp"
"github.com/newrelic/go-agent/v3/newrelic"
)
var once sync.Once
var app *fiber.App
var initMemory []byte
func newApp() *fiber.App {
once.Do(func() {
app = fiber.New()
app.Use(logger.New())
app.Use(requestid.New())
prometheus := fiberprometheus.New("fiber-http")
prometheus.RegisterAt(app, "/metrics")
app.Use(prometheus.Middleware)
// activate New Relic if NEW_RELIC_LICENSE_KEY is in the environment
if newrelicLicenseKey := os.Getenv("NEW_RELIC_LICENSE_KEY"); newrelicLicenseKey != "" {
newrelicAppName := os.Getenv("NEW_RELIC_APP_NAME")
if newrelicAppName == "" {
newrelicAppName = "fiber-http"
}
newrelicApp, err := newrelic.NewApplication(
newrelic.ConfigAppName(newrelicAppName),
newrelic.ConfigLicense(newrelicLicenseKey),
)
if err == nil {
app.Use(NewRelicMiddleware(newrelicApp))
log.Println("New Relic middleware initialized")
} else {
log.Printf("WARNING: failed to initialize New Relic: %s\n", err)
}
}
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("move along, nothing to see here")
})
app.Get("/cpu", func(c *fiber.Ctx) error {
operations, err := strconv.ParseUint(c.Query("operations", "0"), 10, 64)
if err != nil {
return err
}
duration, err := time.ParseDuration(c.Query("duration", "100ms"))
if err != nil {
return err
}
i := uint64(0)
x := 0.0001
start := time.Now()
for time.Since(start) < duration {
if operations != 0 && i == operations {
break
}
x += math.Sqrt(x)
i++
}
runtime := time.Since(start)
return c.SendString(fmt.Sprintf("consumed CPU for %v operations in %v\n", i, runtime.String()))
})
app.Get("/memory", func(c *fiber.Ctx) error {
size, err := bytesize.Parse(c.Query("size", "10MB"))
if err != nil {
return err
}
data := append([]byte{}, make([]byte, size)...)
return c.SendString(fmt.Sprintf("allocated %v (%d bytes) of memory\n", size.String(), len(data)))
})
app.Get("/time", func(c *fiber.Ctx) error {
duration, err := time.ParseDuration(c.Query("duration", "100ms"))
if err != nil {
return err
}
time.Sleep(duration)
return c.SendString(fmt.Sprintf("slept for %v\n", duration.String()))
})
app.Get("/request", func(c *fiber.Ctx) error {
remoteURL := c.Query("url")
if remoteURL == "" {
c.Status(fiber.StatusBadRequest)
return c.SendString("error: missing required query parameter \"url\"")
}
client := fasthttp.Client{}
statusCode, body, err := client.Get(nil, remoteURL)
c.Status(statusCode)
if err != nil {
return err
}
return c.Send(body)
})
app.Use(func(c *fiber.Ctx) error {
return c.SendStatus(fiber.StatusNotFound)
})
})
return app
}
func main() {
// Allocate an initial heap if requested
if sizeEnv := os.Getenv("INIT_MEMORY_SIZE"); sizeEnv != "" {
size, err := bytesize.Parse(sizeEnv)
if err != nil {
log.Fatal(err)
}
initMemory = append(initMemory, make([]byte, size)...)
log.Printf("NOTICE: allocated %v (%d bytes) of memory\n", size.String(), len(initMemory))
}
httpPort := ":8480"
if p := os.Getenv("HTTP_PORT"); p != "" {
httpPort = p
}
app := newApp()
// Load TLS assets
cer, err := tls.LoadX509KeyPair("certs/dev.opsani.com+3.pem", "certs/dev.opsani.com+3-key.pem")
if err != nil {
log.Fatal(err)
}
config := &tls.Config{Certificates: []tls.Certificate{cer}}
// Create TLS port listener
httpsPort := ":8843"
if p := os.Getenv("HTTPS_PORT"); p != "" {
httpsPort = p
}
ln, err := tls.Listen("tcp", httpsPort, config)
if err != nil {
panic(err)
}
// Listen with TLS on HTTPS_PORT (:8843)
go func() {
log.Fatal(app.Listener(ln))
}()
// Listen on HTTP_PORT (:8480)
log.Fatal(app.Listen(httpPort))
}
// NewRelicMiddleware instruments the request with New Relic
func NewRelicMiddleware(app *newrelic.Application) fiber.Handler {
return func(c *fiber.Ctx) error {
// start an HTTP transaction with New Relic
txn := app.StartTransaction(c.Path())
defer txn.End()
// let Fiber process the request
c.Next()
// translate the FastHTTP request & response for New Relic
hdr := make(http.Header)
c.Context().Request.Header.VisitAll(func(k, v []byte) {
sk := string(k)
sv := string(v)
hdr.Set(sk, sv)
})
txn.SetWebRequest(newrelic.WebRequest{
Header: http.Header{},
URL: &url.URL{Path: c.Path()},
Method: c.Method(),
Transport: newrelic.TransportHTTP,
})
// Get a New Relic wrapper for the response writer
rw := txn.SetWebResponse(nil)
rw.WriteHeader(c.Context().Response.StatusCode())
_, err := rw.Write(c.Context().Response.Body())
return err
}
}