forked from karmi/elastic-observability-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.go
78 lines (67 loc) · 1.61 KB
/
app.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
package main
import (
"errors"
"fmt"
"io"
"log"
"math/rand"
"net/http"
"os"
"time"
"github.com/go-redis/redis"
"go.elastic.co/apm"
"go.elastic.co/apm/module/apmgoredis"
"go.elastic.co/apm/module/apmhttp"
)
const (
listenAddr = "0.0.0.0:8000"
)
var (
rdb = redis.NewClient(
&redis.Options{Addr: os.Getenv("REDIS_URL"), Password: os.Getenv("REDIS_PWD")})
)
func main() {
log.SetFlags(0)
rand.Seed(time.Now().UnixNano())
http.Handle(
"/",
apmhttp.Wrap(
http.HandlerFunc(
func(w http.ResponseWriter, req *http.Request) {
// Handle /status
//
if req.URL.Path == "/status" {
io.WriteString(w, "OK")
return
}
// Simulate server errors (5% requests)
//
if rand.Intn(100) > 95 {
apm.CaptureError(req.Context(), errors.New("Simulated server error")).Send()
log.Println("Service unavailable")
http.Error(w, "Service Unavailable", http.StatusServiceUnavailable)
return
}
// Record page view
//
client := apmgoredis.Wrap(rdb).WithContext(req.Context())
i, err := client.Incr("pageviews").Result()
if err != nil {
apm.CaptureError(req.Context(), err).Send()
log.Println("Redis error:", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
// Return response
//
fmt.Fprintf(w, "Hello! This page has been viewed %d times.\n", i)
},
),
),
)
log.Printf("Server starting at %s...", listenAddr)
if err := http.ListenAndServe(listenAddr, nil); err != nil && err != http.ErrServerClosed {
log.Fatal("Unable to start server")
os.Exit(1)
}
}