Beispiel #1
0
func (m authMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// get token from Authorization header
	authToken, err := authtoken.FromRequest(r)
	if err != nil {
		http.Error(w, err.Error(), http.StatusForbidden)
		return
	}

	// context and metadata
	md := metadata.Pairs("traceID", "ABC", "fromName", "api")
	ctx := context.Background()
	ctx = metadata.NewContext(ctx, md)

	// verify token w/ auth service
	_, err = m.VerifyToken(ctx, &auth.AuthRequest{
		AuthToken: authToken,
	})

	if err != nil {
		http.Error(w, "Unauthorized", http.StatusForbidden)
		return
	}

	// Call the next handler on success.
	m.next.ServeHTTP(w, r)
}
Beispiel #2
0
func (s apiServer) requestHandler(w http.ResponseWriter, r *http.Request) {
	// tracing
	tr := trace.New(s.serverName, "URL PATH!")
	defer tr.Finish()

	// metadata
	md := metadata.Pairs("traceID", "TRACEID", "fromName", s.serverName)

	// context
	ctx := context.Background()
	ctx = trace.NewContext(ctx, tr)
	ctx = metadata.NewContext(ctx, md)

	// grab auth token from request
	token, err := authtoken.FromRequest(r)
	if err != nil {
		http.Error(w, err.Error(), http.StatusForbidden)
		return
	}

	// verify token w/ auth service
	_, err = s.VerifyToken(ctx, &auth.Request{token})
	if err != nil {
		http.Error(w, "Unauthorized", http.StatusForbidden)
		return
	}

	// read and validate in/out arguments
	inDate := r.URL.Query().Get("inDate")
	outDate := r.URL.Query().Get("outDate")
	if inDate == "" || outDate == "" {
		http.Error(w, "Please specify inDate / outDate", http.StatusBadRequest)
		return
	}

	// get hotels within geo box
	geoRes, err := s.BoundedBox(ctx, &geo.Request{
		Lo: &geo.Point{Latitude: 400000000, Longitude: -750000000},
		Hi: &geo.Point{Latitude: 420000000, Longitude: -730000000},
	})
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// make reqeusts for profiles and rates
	profileCh := s.getProfiles(ctx, geoRes.HotelIds)
	rateCh := s.getRatePlans(ctx, geoRes.HotelIds, inDate, outDate)

	// wait on profiles reply
	profileReply := <-profileCh
	if err := profileReply.err; err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// wait on rates reply
	rateReply := <-rateCh
	if err := rateReply.err; err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// build the final inventory response
	inventory := inventory{
		Hotels:    profileReply.hotels,
		RatePlans: rateReply.ratePlans,
	}

	// encode JSON for rendering
	encoder := json.NewEncoder(w)
	if err = encoder.Encode(inventory); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}