This repository has been archived by the owner on May 24, 2022. It is now read-only.
/
main.go
192 lines (158 loc) · 4.83 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
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
package main
import (
"context"
"encoding/base64"
"errors"
_ "expvar"
"net/http"
_ "net/http/pprof"
"strings"
"golang.org/x/net/trace"
"github.com/google/uuid"
"github.com/nicocesar/booking/api/hotel/proto"
"github.com/nicocesar/booking/srv/auth/proto"
"github.com/nicocesar/booking/srv/geo/proto"
"github.com/nicocesar/booking/srv/profile/proto"
"github.com/nicocesar/booking/srv/rate/proto"
"github.com/micro/go-micro/v2"
"github.com/micro/go-micro/v2/client"
merr "github.com/micro/go-micro/v2/errors"
"github.com/micro/go-micro/v2/metadata"
)
const (
BASIC_SCHEMA string = "Basic "
BEARER_SCHEMA string = "Bearer "
)
type profileResults struct {
hotels []*profile.Hotel
err error
}
type rateResults struct {
ratePlans []*rate.RatePlan
err error
}
type Hotel struct {
Client client.Client
}
func (s *Hotel) Rates(ctx context.Context, req *hotel.Request, rsp *hotel.Response) error {
// tracing
tr := trace.New("api.v1", "Hotel.Rates")
defer tr.Finish()
// context
ctx = trace.NewContext(ctx, tr)
md, ok := metadata.FromContext(ctx)
if !ok {
md = metadata.Metadata{}
}
// add a unique request id to context
traceID := uuid.New()
// make copy
tmd := metadata.Metadata{}
for k, v := range md {
tmd[k] = v
}
tmd["traceID"] = traceID.String()
tmd["fromName"] = "api.v1"
ctx = metadata.NewContext(ctx, tmd)
// token from request headers
token, err := getToken(md)
if err != nil {
return merr.Forbidden("api.hotel.rates", err.Error())
}
// verify token w/ auth service
authClient := auth.NewAuthService("go.micro.srv.auth", s.Client)
if _, err = authClient.VerifyToken(ctx, &auth.Request{AuthToken: token}); err != nil {
return merr.Unauthorized("api.hotel.rates", "Unauthorized")
}
// checkin and checkout date query params
inDate, outDate := req.InDate, req.OutDate
if inDate == "" || outDate == "" {
return merr.BadRequest("api.hotel.rates", "Please specify inDate/outDate params")
}
// finds nearby hotels
// TODO(hw): use lat/lon from request params
geoClient := geo.NewGeoService("go.micro.srv.geo", s.Client)
nearby, err := geoClient.Nearby(ctx, &geo.Request{
Lat: 51.502973,
Lon: -0.114723,
})
if err != nil {
return merr.InternalServerError("api.hotel.rates", err.Error())
}
// make requests for profiles and rates
profileCh := getHotelProfiles(s.Client, ctx, nearby.HotelIds)
rateCh := getRatePlans(s.Client, ctx, nearby.HotelIds, inDate, outDate)
// wait on profiles reply
profileReply := <-profileCh
if err := profileReply.err; err != nil {
return merr.InternalServerError("api.hotel.rates", err.Error())
}
// wait on rates reply
rateReply := <-rateCh
if err := rateReply.err; err != nil {
return merr.InternalServerError("api.hotel.rates", err.Error())
}
rsp.Hotels = profileReply.hotels
rsp.RatePlans = rateReply.ratePlans
return nil
}
func getToken(md metadata.Metadata) (string, error) {
// Grab the raw Authorization header
authHeader := md["Authorization"]
if authHeader == "" {
return "", errors.New("Authorization header required")
}
// Confirm the request is sending Basic Authentication credentials.
if !strings.HasPrefix(authHeader, BASIC_SCHEMA) && !strings.HasPrefix(authHeader, BEARER_SCHEMA) {
return "", errors.New("Authorization requires Basic/Bearer scheme")
}
// Get the token from the request header
// The first six characters are skipped - e.g. "Basic ".
if strings.HasPrefix(authHeader, BASIC_SCHEMA) {
str, err := base64.StdEncoding.DecodeString(authHeader[len(BASIC_SCHEMA):])
if err != nil {
return "", errors.New("Base64 encoding issue")
}
creds := strings.Split(string(str), ":")
return creds[0], nil
}
return authHeader[len(BEARER_SCHEMA):], nil
}
func getRatePlans(c client.Client, ctx context.Context, hotelIDs []string, inDate string, outDate string) chan rateResults {
rateClient := rate.NewRateService("go.micro.srv.rate", c)
ch := make(chan rateResults, 1)
go func() {
res, err := rateClient.GetRates(ctx, &rate.Request{
HotelIds: hotelIDs,
InDate: inDate,
OutDate: outDate,
})
ch <- rateResults{res.RatePlans, err}
}()
return ch
}
func getHotelProfiles(c client.Client, ctx context.Context, hotelIDs []string) chan profileResults {
profileClient := profile.NewProfileService("go.micro.srv.profile", c)
ch := make(chan profileResults, 1)
go func() {
res, err := profileClient.GetProfiles(ctx, &profile.Request{
HotelIds: hotelIDs,
Locale: "en",
})
ch <- profileResults{res.Hotels, err}
}()
return ch
}
func main() {
// trace library patched for demo purposes.
// https://github.com/golang/net/blob/master/trace/trace.go#L94
trace.AuthRequest = func(req *http.Request) (any, sensitive bool) {
return true, true
}
service := micro.NewService(
micro.Name("go.micro.api.hotel"),
)
service.Init()
hotel.RegisterHotelHandler(service.Server(), &Hotel{service.Client()})
service.Run()
}