-
Notifications
You must be signed in to change notification settings - Fork 3
/
ping_server.go
66 lines (59 loc) · 1.69 KB
/
ping_server.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
package main
import (
"encoding/json"
"fmt"
"log"
"math/rand"
"net/http"
"time"
"go.uber.org/zap"
)
// PingServer is a webserver that can be started.
type PingServer interface {
Start()
}
type pingServer struct {
config *HTTPConfig
randomGenerator *rand.Rand
errorRate float64
logger *zap.SugaredLogger
instanceid string
}
// NewPingServer creates a new PingServer obviously.
func NewPingServer(serverConfig *HTTPConfig, errorRate float64, instanceid string) PingServer {
logger, err := zap.NewDevelopment()
sugar := logger.Sugar()
if err != nil {
log.Fatalf("can't initialize zap logger: %v", err)
}
return &pingServer{
config: serverConfig,
randomGenerator: rand.New(rand.NewSource(time.Now().UnixNano())),
errorRate: errorRate,
logger: sugar,
instanceid: instanceid,
}
}
func (ps *pingServer) Start() {
ps.logger.Infof("starting ping server with errorRate: '%v', config: '%#v'", ps.errorRate, ps.config)
http.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) {
f := ps.randomGenerator.Float64()
if f < ps.errorRate {
http.Error(w, "no wai!", http.StatusTeapot)
return
}
err := json.NewEncoder(w).Encode(fmt.Sprintf("pongpong from '%s'", ps.instanceid))
if err != nil {
ps.logger.Errorf("error encoding json response '%v'", err)
}
ps.logger.Infof("Got pinged by '%s', sent a 'pong'!", r.RemoteAddr)
})
log.Fatal(ps.listenAndServe())
}
func (ps *pingServer) listenAndServe() error {
address := fmt.Sprintf(":%v", ps.config.port)
if !ps.config.isSecure() {
return http.ListenAndServe(address, nil)
}
return http.ListenAndServeTLS(address, ps.config.certFile, ps.config.keyFile, nil)
}