-
Notifications
You must be signed in to change notification settings - Fork 8
/
api_gateway.go
103 lines (91 loc) · 2.55 KB
/
api_gateway.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
package main
import (
"fmt"
"net/http"
"github.com/gin-contrib/opengintracing"
"github.com/gin-gonic/gin"
"github.com/opentracing/opentracing-go"
"github.com/uber/jaeger-client-go"
"github.com/uber/jaeger-client-go/zipkin"
)
func main() {
// Configure tracing
propagator := zipkin.NewZipkinB3HTTPHeaderPropagator()
trace, closer := jaeger.NewTracer(
"api_gateway",
jaeger.NewConstSampler(true),
jaeger.NewNullReporter(),
jaeger.TracerOptions.Injector(opentracing.HTTPHeaders, propagator),
jaeger.TracerOptions.Extractor(opentracing.HTTPHeaders, propagator),
jaeger.TracerOptions.ZipkinSharedRPCSpan(true),
)
defer closer.Close()
opentracing.SetGlobalTracer(trace)
// Set up routes
r := gin.Default()
r.POST("/service1",
opengintracing.NewSpan(trace, "forward to service 1"),
service1handler)
r.POST("/service2",
opengintracing.NewSpan(trace, "forward to service 2"),
service2handler)
r.Run(":8000")
}
func printHeaders(message string, header http.Header) {
fmt.Println(message)
for k, v := range header {
fmt.Printf("%s: %s\n", k, v)
}
}
func service1handler(c *gin.Context) {
span, found := opengintracing.GetSpan(c)
if found == false {
fmt.Println("Span not found")
c.AbortWithStatus(http.StatusInternalServerError)
return
}
req, _ := http.NewRequest("POST", "http://localhost:8001", nil)
opentracing.GlobalTracer().Inject(
span.Context(),
opentracing.HTTPHeaders,
opentracing.HTTPHeadersCarrier(req.Header))
printHeaders("Incoming Headers", c.Request.Header)
printHeaders("Outgoing Headers", req.Header)
client := http.Client{}
resp, err := client.Do(req)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
if resp.StatusCode != http.StatusOK {
c.AbortWithStatus(http.StatusInternalServerError)
return
}
c.Status(http.StatusOK)
}
func service2handler(c *gin.Context) {
span, found := opengintracing.GetSpan(c)
if found == false {
fmt.Println("Span not found")
c.AbortWithStatus(http.StatusInternalServerError)
return
}
req, _ := http.NewRequest("POST", "http://localhost:8002", nil)
opentracing.GlobalTracer().Inject(
span.Context(),
opentracing.HTTPHeaders,
opentracing.HTTPHeadersCarrier(req.Header))
printHeaders("Incoming Headers", c.Request.Header)
printHeaders("Outgoing Headers", req.Header)
client := http.Client{}
resp, err := client.Do(req)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
if resp.StatusCode != http.StatusOK {
c.AbortWithStatus(http.StatusInternalServerError)
return
}
c.Status(http.StatusOK)
}