/
main.go
62 lines (49 loc) · 1.45 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
package main
import (
"encoding/json"
"log"
"net/http"
"strings"
opentracing "github.com/opentracing/opentracing-go"
otlog "github.com/opentracing/opentracing-go/log"
"github.com/PacktPublishing/Mastering-Distributed-Tracing/Chapter04/go/exercise4b/people"
"github.com/PacktPublishing/Mastering-Distributed-Tracing/Chapter04/go/lib/tracing"
)
var repo *people.Repository
func main() {
tracer, closer := tracing.Init("go-4-bigbrother")
defer closer.Close()
opentracing.SetGlobalTracer(tracer)
repo = people.NewRepository()
defer repo.Close()
http.HandleFunc("/getPerson/", handleGetPerson)
log.Print("Listening on http://localhost:8081/")
log.Fatal(http.ListenAndServe(":8081", nil))
}
func handleGetPerson(w http.ResponseWriter, r *http.Request) {
spanCtx, _ := opentracing.GlobalTracer().Extract(
opentracing.HTTPHeaders,
opentracing.HTTPHeadersCarrier(r.Header),
)
span := opentracing.GlobalTracer().StartSpan(
"/getPerson",
opentracing.ChildOf(spanCtx),
)
defer span.Finish()
ctx := opentracing.ContextWithSpan(r.Context(), span)
name := strings.TrimPrefix(r.URL.Path, "/getPerson/")
person, err := repo.GetPerson(ctx, name)
if err != nil {
span.SetTag("error", true)
span.LogFields(otlog.Error(err))
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
span.LogKV(
"name", person.Name,
"title", person.Title,
"description", person.Description,
)
bytes, _ := json.Marshal(person)
w.Write(bytes)
}