Exemple #1
0
// MakeHTTPHandler mounts the endpoints into a REST-y HTTP handler.
func MakeHTTPHandler(ctx context.Context, e Endpoints, imagePath string, logger log.Logger) http.Handler {
	r := mux.NewRouter().StrictSlash(false)
	options := []httptransport.ServerOption{
		httptransport.ServerErrorLogger(logger),
		httptransport.ServerErrorEncoder(encodeError),
	}

	// GET /catalogue       List
	// GET /catalogue/size  Count
	// GET /catalogue/{id}  Get
	// GET /tags            Tags
	// GET /health		Health Check

	r.Methods("GET").Path("/catalogue").Handler(httptransport.NewServer(
		ctx,
		e.ListEndpoint,
		decodeListRequest,
		encodeListResponse,
		options...,
	))
	r.Methods("GET").Path("/catalogue/size").Handler(httptransport.NewServer(
		ctx,
		e.CountEndpoint,
		decodeCountRequest,
		encodeResponse,
		options...,
	))
	r.Methods("GET").Path("/catalogue/{id}").Handler(httptransport.NewServer(
		ctx,
		e.GetEndpoint,
		decodeGetRequest,
		encodeGetResponse, // special case, this one can have an error
		options...,
	))
	r.Methods("GET").Path("/tags").Handler(httptransport.NewServer(
		ctx,
		e.TagsEndpoint,
		decodeTagsRequest,
		encodeResponse,
		options...,
	))
	r.Methods("GET").PathPrefix("/catalogue/images/").Handler(http.StripPrefix(
		"/catalogue/images/",
		http.FileServer(http.Dir(imagePath)),
	))
	r.Methods("GET").PathPrefix("/health").Handler(httptransport.NewServer(
		ctx,
		e.HealthEndpoint,
		decodeHealthRequest,
		encodeHealthResponse,
		options...,
	))
	r.Handle("/metrics", promhttp.Handler())
	return r
}
func createHealthCheckRouter(logger kitlog.Logger, ctx context.Context, healthCheckEndpoint endpoint.HealthCheckServicer) *mux.Router {
	router := mux.NewRouter()
	router.Handle("/healthcheck",
		kithttp.NewServer(
			ctx,
			healthCheckEndpoint.Run,
			func(context.Context, *http.Request) (interface{}, error) { return struct{}{}, nil },
			encodeHealthCheckHTTPResponse,
			kithttp.ServerErrorEncoder(errorEncoder),
			kithttp.ServerErrorLogger(logger),
		)).Methods(getHTTPMethod)
	return router
}
func createApplicationRouter(logger kitlog.Logger, ctx context.Context, c *config.Configuration, sensorReadingsServicer endpoint.SensorReadingsServicer) *mux.Router {
	router := mux.NewRouter()
	router.Handle("/api/v1/sensor_readings",
		kithttp.NewServer(
			ctx,
			endpoint.VerifyAPIKey(c.APITokens)(sensorReadingsServicer.HandleMeasurementMessage),
			decodeSensorReadingsHTTPRequest,
			encodeSensorReadingsHTTPResponse,
			kithttp.ServerErrorEncoder(errorEncoder),
			kithttp.ServerErrorLogger(logger),
		)).Methods(postHTTPMethod)
	return router
}
Exemple #4
0
// Handler returns go-kit http transport server
// of the given definition
func (s Service) Handler() http.Handler {
	ep := s.Middlewares.Chain()(s.Endpoint)
	options := append([]httptransport.ServerOption{
		httptransport.ServerBefore(s.Before...),
		httptransport.ServerAfter(s.After...),
		httptransport.ServerErrorEncoder(s.ErrorEncoder),
	}, s.Options...)
	return httptransport.NewServer(
		s.Context,
		ep,
		s.DecodeFunc,
		s.EncodeFunc,
		options...)
}
Exemple #5
0
func main() {
	flag.Usage = usage
	flag.Parse()
	a := flag.Args()

	var mode = ""
	if len(a) > 0 {
		mode = a[0]
	}

	switch mode {
	case "server":
		var svc StringService
		options := []httptrans.ServerOption{httptrans.ServerErrorEncoder(func(ctx context.Context, err error, w http.ResponseWriter) {
			w.WriteHeader(500)
			encoding.JSON(1).EncodeResponse()(ctx, w, err)
		}),
		}
		trans.ServersForEndpointsWithOptions(svc, []trans.ServerLayer{}, options)
		http.ListenAndServe(args.httpPort, nil)
	case "client":
		if len(a) < 3 {
			usage()
			return
		}

		client := trans.NewClient("127.0.0.1" + args.httpPort)

		cmd := a[1]
		arg := a[2]
		switch cmd {
		case "uppercase":
			str, err := client.Uppercase(arg)
			fmt.Printf("\t\"%s\".Uppercase: \"%s\", err: %s\n", arg, str, err)
		case "count":
			count := client.Count(arg)
			fmt.Printf("\t\"%s\".Count: %d\n", arg, count)
		}

	default:
		usage()
	}

}
Exemple #6
0
// MakeHandler returns a handler for the tracking service.
func MakeHandler(ctx context.Context, ts Service, logger kitlog.Logger) http.Handler {
	r := mux.NewRouter()

	opts := []kithttp.ServerOption{
		kithttp.ServerErrorLogger(logger),
		kithttp.ServerErrorEncoder(encodeError),
	}

	trackCargoHandler := kithttp.NewServer(
		ctx,
		makeTrackCargoEndpoint(ts),
		decodeTrackCargoRequest,
		encodeResponse,
		opts...,
	)

	r.Handle("/tracking/v1/cargos/{id}", trackCargoHandler).Methods("GET")

	return r
}
Exemple #7
0
// MakeHandler returns a handler for the handling service.
func MakeHandler(ctx context.Context, hs Service, logger kitlog.Logger) http.Handler {
	r := mux.NewRouter()

	opts := []kithttp.ServerOption{
		kithttp.ServerErrorLogger(logger),
		kithttp.ServerErrorEncoder(encodeError),
	}

	registerIncidentHandler := kithttp.NewServer(
		ctx,
		makeRegisterIncidentEndpoint(hs),
		decodeRegisterIncidentRequest,
		encodeResponse,
		opts...,
	)

	r.Handle("/handling/v1/incidents", registerIncidentHandler).Methods("POST")

	return r
}
Exemple #8
0
func TestServerErrorEncoder(t *testing.T) {
	errTeapot := errors.New("teapot")
	code := func(err error) int {
		if err == errTeapot {
			return http.StatusTeapot
		}
		return http.StatusInternalServerError
	}
	handler := httptransport.NewServer(
		context.Background(),
		func(context.Context, interface{}) (interface{}, error) { return struct{}{}, errTeapot },
		func(*http.Request) (interface{}, error) { return struct{}{}, nil },
		func(http.ResponseWriter, interface{}) error { return nil },
		httptransport.ServerErrorEncoder(func(w http.ResponseWriter, err error) { w.WriteHeader(code(err)) }),
	)
	server := httptest.NewServer(handler)
	defer server.Close()
	resp, _ := http.Get(server.URL)
	if want, have := http.StatusTeapot, resp.StatusCode; want != have {
		t.Errorf("want %d, have %d", want, have)
	}
}
Exemple #9
0
// MakeHTTPHandler returns a handler that makes a set of endpoints available
// on predefined paths.
func MakeHTTPHandler(ctx context.Context, endpoints Endpoints, tracer stdopentracing.Tracer, logger log.Logger) http.Handler {
	options := []httptransport.ServerOption{
		httptransport.ServerErrorEncoder(errorEncoder),
		httptransport.ServerErrorLogger(logger),
	}
	m := http.NewServeMux()
	m.Handle("/sum", httptransport.NewServer(
		ctx,
		endpoints.SumEndpoint,
		DecodeHTTPSumRequest,
		EncodeHTTPGenericResponse,
		append(options, httptransport.ServerBefore(opentracing.FromHTTPRequest(tracer, "Sum", logger)))...,
	))
	m.Handle("/concat", httptransport.NewServer(
		ctx,
		endpoints.ConcatEndpoint,
		DecodeHTTPConcatRequest,
		EncodeHTTPGenericResponse,
		append(options, httptransport.ServerBefore(opentracing.FromHTTPRequest(tracer, "Concat", logger)))...,
	))
	return m
}
Exemple #10
0
// MakeHTTPHandler mounts the endpoints into a REST-y HTTP handler.
func MakeHTTPHandler(ctx context.Context, e Endpoints, logger log.Logger) http.Handler {
	r := mux.NewRouter().StrictSlash(false)
	options := []httptransport.ServerOption{
		httptransport.ServerErrorLogger(logger),
		httptransport.ServerErrorEncoder(encodeError),
	}

	// GET /login       Login
	// GET /register    Register
	// GET /health      Health Check

	r.Methods("GET").Path("/login").Handler(httptransport.NewServer(
		ctx,
		e.LoginEndpoint,
		decodeLoginRequest,
		encodeResponse,
		options...,
	))
	r.Methods("POST").Path("/register").Handler(httptransport.NewServer(
		ctx,
		e.RegisterEndpoint,
		decodeRegisterRequest,
		encodeResponse,
		options...,
	))
	r.Methods("GET").PathPrefix("/customers").Handler(httptransport.NewServer(
		ctx,
		e.UserGetEndpoint,
		decodeGetRequest,
		encodeResponse,
		options...,
	))
	r.Methods("GET").PathPrefix("/cards").Handler(httptransport.NewServer(
		ctx,
		e.CardGetEndpoint,
		decodeGetRequest,
		encodeResponse,
		options...,
	))
	r.Methods("GET").PathPrefix("/addresses").Handler(httptransport.NewServer(
		ctx,
		e.AddressGetEndpoint,
		decodeGetRequest,
		encodeResponse,
		options...,
	))
	r.Methods("POST").Path("/customers").Handler(httptransport.NewServer(
		ctx,
		e.UserPostEndpoint,
		decodeUserRequest,
		encodeResponse,
		options...,
	))
	r.Methods("POST").Path("/addresses").Handler(httptransport.NewServer(
		ctx,
		e.AddressPostEndpoint,
		decodeAddressRequest,
		encodeResponse,
		options...,
	))
	r.Methods("POST").Path("/cards").Handler(httptransport.NewServer(
		ctx,
		e.CardPostEndpoint,
		decodeCardRequest,
		encodeResponse,
		options...,
	))
	r.Methods("DELETE").PathPrefix("/").Handler(httptransport.NewServer(
		ctx,
		e.DeleteEndpoint,
		decodeDeleteRequest,
		encodeResponse,
		options...,
	))
	r.Methods("GET").PathPrefix("/health").Handler(httptransport.NewServer(
		ctx,
		e.HealthEndpoint,
		decodeHealthRequest,
		encodeHealthResponse,
		options...,
	))
	r.Handle("/metrics", promhttp.Handler())
	return r
}
Exemple #11
0
// MakeHTTPHandler mounts all of the service endpoints into an http.Handler.
// Useful in a restsvc server.
func MakeHTTPHandler(ctx context.Context, s Service, logger log.Logger) http.Handler {
	r := mux.NewRouter()
	e := MakeServerEndpoints(s)
	options := []httptransport.ServerOption{
		httptransport.ServerErrorLogger(logger),
		httptransport.ServerErrorEncoder(encodeError),
	}

	// POST    /configs/                          adds another config
	// GET     /configs/:id                       retrieves the given config by id
	// PUT     /configs/:id                       post updated config information about the config
	// PATCH   /configs/:id                       partial updated config information
	// DELETE  /configs/:id                       remove the given config
	// GET     /configs/:id/channels/            retrieve channels associated with the config
	// GET     /configs/:id/channels/:channelID  retrieve a particular config channel
	// POST    /configs/:id/channels/            add a new channel
	// DELETE  /configs/:id/channels/:channelID  remove an channel

	r.Methods("POST").Path("/api/configs/").Handler(httptransport.NewServer(
		ctx,
		e.PostConfigEndpoint,
		decodePostConfigRequest,
		encodeResponse,
		options...,
	))
	r.Methods("GET").Path("/api/configs/{id}").Handler(httptransport.NewServer(
		ctx,
		e.GetConfigEndpoint,
		decodeGetConfigRequest,
		encodeResponse,
		options...,
	))
	r.Methods("PUT").Path("/api/configs/{id}").Handler(httptransport.NewServer(
		ctx,
		e.PutConfigEndpoint,
		decodePutConfigRequest,
		encodeResponse,
		options...,
	))
	r.Methods("PATCH").Path("/api/configs/{id}").Handler(httptransport.NewServer(
		ctx,
		e.PatchConfigEndpoint,
		decodePatchConfigRequest,
		encodeResponse,
		options...,
	))
	r.Methods("DELETE").Path("/api/configs/{id}").Handler(httptransport.NewServer(
		ctx,
		e.DeleteConfigEndpoint,
		decodeDeleteConfigRequest,
		encodeResponse,
		options...,
	))
	r.Methods("GET").Path("/api/configs/{id}/channels/").Handler(httptransport.NewServer(
		ctx,
		e.GetChannelsEndpoint,
		decodeGetChannelsRequest,
		encodeResponse,
		options...,
	))
	r.Methods("GET").Path("/api/configs/{id}/channels/{channelID}").Handler(httptransport.NewServer(
		ctx,
		e.GetChannelEndpoint,
		decodeGetChannelRequest,
		encodeResponse,
		options...,
	))
	r.Methods("POST").Path("/api/configs/{id}/channels/").Handler(httptransport.NewServer(
		ctx,
		e.PostChannelEndpoint,
		decodePostChannelRequest,
		encodeResponse,
		options...,
	))
	r.Methods("DELETE").Path("/api/configs/{id}/channels/{channelID}").Handler(httptransport.NewServer(
		ctx,
		e.DeleteChannelEndpoint,
		decodeDeleteChannelRequest,
		encodeResponse,
		options...,
	))

	// Convenience routes to help consumers nesting limitations
	r.Methods("GET").Path("/api/channels/{channelID}/notes/").Handler(httptransport.NewServer(
		ctx,
		e.GetNotesEndpoint,
		decodeGetNotesRequest,
		encodeResponse,
		options...,
	))
	r.Methods("GET").Path("/api/channels/{channelID}").Handler(httptransport.NewServer(
		ctx,
		e.GetChannelEndpoint,
		decodeGetChannelRequest,
		encodeResponse,
		options...,
	))

	return r
}
Exemple #12
0
func makeHandler(ctx context.Context, s ProfileService, logger kitlog.Logger) stdhttp.Handler {
	e := makeEndpoints(s)
	r := mux.NewRouter()

	commonOptions := []kithttp.ServerOption{
		kithttp.ServerErrorLogger(logger),
		kithttp.ServerErrorEncoder(encodeError),
	}

	// POST    /profiles                           adds another profile
	// GET     /profiles/:id                       retrieves the given profile by id
	// PUT     /profiles/:id                       post updated profile information about the profile
	// PATCH   /profiles/:id                       partial updated profile information
	// DELETE  /profiles/:id                       remove the given profile
	// GET     /profiles/:id/addresses             retrieve addresses associated with the profile
	// GET     /profiles/:id/addresses/:addressID  retrieve a particular profile address
	// POST    /profiles/:id/addresses             add a new address
	// DELETE  /profiles/:id/addresses/:addressID  remove an address

	r.Methods("POST").Path("/profiles/").Handler(kithttp.NewServer(
		ctx,
		e.postProfileEndpoint,
		decodePostProfileRequest,
		encodeResponse,
		commonOptions...,
	))
	r.Methods("GET").Path("/profiles/{id}").Handler(kithttp.NewServer(
		ctx,
		e.getProfileEndpoint,
		decodeGetProfileRequest,
		encodeResponse,
		commonOptions...,
	))
	r.Methods("PUT").Path("/profiles/{id}").Handler(kithttp.NewServer(
		ctx,
		e.putProfileEndpoint,
		decodePutProfileRequest,
		encodeResponse,
		commonOptions...,
	))
	r.Methods("PATCH").Path("/profiles/{id}").Handler(kithttp.NewServer(
		ctx,
		e.patchProfileEndpoint,
		decodePatchProfileRequest,
		encodeResponse,
		commonOptions...,
	))
	r.Methods("DELETE").Path("/profiles/{id}").Handler(kithttp.NewServer(
		ctx,
		e.deleteProfileEndpoint,
		decodeDeleteProfileRequest,
		encodeResponse,
		commonOptions...,
	))
	r.Methods("GET").Path("/profiles/{id}/addresses/").Handler(kithttp.NewServer(
		ctx,
		e.getAddressesEndpoint,
		decodeGetAddressesRequest,
		encodeResponse,
		commonOptions...,
	))
	r.Methods("GET").Path("/profiles/{id}/addresses/{addressID}").Handler(kithttp.NewServer(
		ctx,
		e.getAddressEndpoint,
		decodeGetAddressRequest,
		encodeResponse,
		commonOptions...,
	))
	r.Methods("POST").Path("/profiles/{id}/addresses/").Handler(kithttp.NewServer(
		ctx,
		e.postAddressEndpoint,
		decodePostAddressRequest,
		encodeResponse,
		commonOptions...,
	))
	r.Methods("DELETE").Path("/profiles/{id}/addresses/{addressID}").Handler(kithttp.NewServer(
		ctx,
		e.deleteAddressEndpoint,
		decodeDeleteAddressRequest,
		encodeResponse,
		commonOptions...,
	))
	return r
}
Exemple #13
0
func main() {
	port := os.Getenv("PORT")
	pgURI := os.Getenv("DATABASE_URL")

	if port == "" {
		port = "8080"
	}

	fmt.Printf("Connecting to %s\n", pgURI)
	pg, err := sql.Open("postgres", pgURI)
	if err != nil {
		panic(err)
	}

	router := mux.NewRouter()

	ctx := context.Background()
	svc := gledger.NewAccountService(
		db.SaveAccount(pg.Exec),
		db.AllAccounts(pg.Query),
		db.ReadAccount(pg.QueryRow),
	)
	txnSvc := gledger.NewTransactionService(
		db.SaveTransaction(pg),
		db.TransactionsForAccount(pg),
	)
	envSvc := gledger.NewEnvelopeService(
		db.SaveEnvelope(pg.Exec),
		db.AllEnvelopes(pg.Query),
	)

	httpOptions := []httptransport.ServerOption{httptransport.ServerErrorEncoder(errorEncoder)}

	router.HandleFunc(
		"/accounts",
		httptransport.NewServer(
			ctx,
			makeCreateAccountEndpoint(svc),
			decodeCreateAccountRequest,
			created(encodeResponse),
			httpOptions...,
		).ServeHTTP,
	).Methods("POST")
	router.HandleFunc(
		"/accounts",
		httptransport.NewServer(
			ctx,
			makeAllAccountsEndpoint(svc),
			emptyRequest,
			encodeResponse,
			httpOptions...,
		).ServeHTTP,
	).Methods("GET")

	router.HandleFunc(
		"/accounts/{uuid}",
		httptransport.NewServer(
			ctx,
			makeReadAccountEndpoint(svc),
			decodeReadAccountRequest,
			encodeResponse,
			httpOptions...,
		).ServeHTTP,
	).Methods("GET")
	router.HandleFunc(
		"/transactions",
		httptransport.NewServer(
			ctx,
			makeCreateTransactionEndpoint(txnSvc),
			decodeCreateTransactionRequest,
			created(encodeResponse),
			httpOptions...,
		).ServeHTTP,
	).Methods("POST")

	router.HandleFunc(
		"/accounts/{uuid}/transactions",
		httptransport.NewServer(
			ctx,
			makeReadAccountTransactionsEndpoint(txnSvc),
			decodeReadAccountTransactionsRequest,
			encodeResponse,
			httpOptions...,
		).ServeHTTP,
	).Methods("GET")

	router.HandleFunc(
		"/envelopes",
		httptransport.NewServer(
			ctx,
			makeCreateEnvelopeEndpoint(envSvc),
			decodeCreateEnvelopeRequest,
			created(encodeResponse),
			httpOptions...,
		).ServeHTTP,
	).Methods("POST")
	router.HandleFunc(
		"/envelopes",
		httptransport.NewServer(
			ctx,
			makeAllEnvelopesEndpoint(envSvc),
			emptyRequest,
			encodeResponse,
			httpOptions...,
		).ServeHTTP,
	).Methods("GET")

	handler := cors.New(cors.Options{
		AllowedOrigins: []string{"http://localhost:4200", "https://gledger-web.herokuapp.com"},
	}).Handler(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
		start := time.Now()
		router.ServeHTTP(res, req)
		end := time.Now()
		log.Printf("%s %s %s\n", req.Method, req.URL, end.Sub(start))
	}))
	log.Fatal(http.ListenAndServe(":"+port, handler))
}
Exemple #14
0
// MakeHandler returns a handler for the booking service.
func MakeHandler(ctx context.Context, bs Service, logger kitlog.Logger) http.Handler {
	opts := []kithttp.ServerOption{
		kithttp.ServerErrorLogger(logger),
		kithttp.ServerErrorEncoder(encodeError),
	}

	bookCargoHandler := kithttp.NewServer(
		ctx,
		makeBookCargoEndpoint(bs),
		decodeBookCargoRequest,
		encodeResponse,
		opts...,
	)
	loadCargoHandler := kithttp.NewServer(
		ctx,
		makeLoadCargoEndpoint(bs),
		decodeLoadCargoRequest,
		encodeResponse,
		opts...,
	)
	requestRoutesHandler := kithttp.NewServer(
		ctx,
		makeRequestRoutesEndpoint(bs),
		decodeRequestRoutesRequest,
		encodeResponse,
		opts...,
	)
	assignToRouteHandler := kithttp.NewServer(
		ctx,
		makeAssignToRouteEndpoint(bs),
		decodeAssignToRouteRequest,
		encodeResponse,
		opts...,
	)
	changeDestinationHandler := kithttp.NewServer(
		ctx,
		makeChangeDestinationEndpoint(bs),
		decodeChangeDestinationRequest,
		encodeResponse,
		opts...,
	)
	listCargosHandler := kithttp.NewServer(
		ctx,
		makeListCargosEndpoint(bs),
		decodeListCargosRequest,
		encodeResponse,
		opts...,
	)
	listLocationsHandler := kithttp.NewServer(
		ctx,
		makeListLocationsEndpoint(bs),
		decodeListLocationsRequest,
		encodeResponse,
		opts...,
	)

	r := mux.NewRouter()

	r.Handle("/booking/v1/cargos", bookCargoHandler).Methods("POST")
	r.Handle("/booking/v1/cargos", listCargosHandler).Methods("GET")
	r.Handle("/booking/v1/cargos/{id}", loadCargoHandler).Methods("GET")
	r.Handle("/booking/v1/cargos/{id}/request_routes", requestRoutesHandler).Methods("GET")
	r.Handle("/booking/v1/cargos/{id}/assign_to_route", assignToRouteHandler).Methods("POST")
	r.Handle("/booking/v1/cargos/{id}/change_destination", changeDestinationHandler).Methods("POST")
	r.Handle("/booking/v1/locations", listLocationsHandler).Methods("GET")
	r.Handle("/booking/v1/docs", http.StripPrefix("/booking/v1/docs", http.FileServer(http.Dir("booking/docs"))))

	return r
}
Exemple #15
0
func NewApi(ng engine.Engine) *Api {
	api := &Api{router: NewRouter(), ng: ng}

	api.router.NotFoundHandler(http.HandlerFunc(api.notFoundHandler))
	api.router.AddHandler(RouterArguments{Path: "/", Methods: []string{"GET"}, Handler: homeHandler})
	ctx := context.Background()

	ffs := features.New(api.ng)

	createHandler := httptransport.NewServer(
		ctx,
		CreateEndpoint(ffs),
		decodeFeatureFlagRequest,
		encodeResponse,
		httptransport.ServerErrorEncoder(handleErrorEncoder),
	)
	api.router.AddHandler(RouterArguments{Path: "/features", Methods: []string{"POST"}, HandlerNormal: createHandler})

	updateHandler := httptransport.NewServer(
		ctx,
		UpdateEndpoint(ffs),
		decodeFeatureFlagRequest,
		encodeResponse,
		httptransport.ServerErrorEncoder(handleErrorEncoder),
	)
	api.router.AddHandler(RouterArguments{Path: "/features/{feature_key}", Methods: []string{"PUT"}, HandlerNormal: updateHandler})

	deleteHandler := httptransport.NewServer(
		ctx,
		DeleteEndpoint(ffs),
		decodeFeatureFlagQueryString,
		encodeResponse,
		httptransport.ServerErrorEncoder(handleErrorEncoder),
	)
	api.router.AddHandler(RouterArguments{Path: "/features/{feature_key}", Methods: []string{"DELETE"}, HandlerNormal: deleteHandler})

	findHandler := httptransport.NewServer(
		ctx,
		FindEndpoint(ffs),
		decodeFeatureFlagQueryString,
		encodeResponse,
		httptransport.ServerErrorEncoder(handleErrorEncoder),
	)
	api.router.AddHandler(RouterArguments{Path: "/features/{feature_key}", Methods: []string{"GET"}, HandlerNormal: findHandler})

	listHandler := httptransport.NewServer(
		ctx,
		ListEndpoint(ffs),
		decodeFeatureFlagQueryString,
		encodeResponse,
		httptransport.ServerErrorEncoder(handleErrorEncoder),
	)
	api.router.AddHandler(RouterArguments{Path: "/features", Methods: []string{"GET"}, HandlerNormal: listHandler})

	validateHandler := httptransport.NewServer(
		ctx,
		ValidateEndpoint(ffs),
		decodeValidationRequest,
		encodeResponse,
		httptransport.ServerErrorEncoder(handleErrorEncoder),
	)
	api.router.AddHandler(RouterArguments{Path: "/features", Methods: []string{"PUT"}, HandlerNormal: validateHandler})

	return api
}
Exemple #16
0
// MakeHTTPHandler mounts all of the service endpoints into an http.Handler.
// Useful in a profilesvc server.
func MakeHTTPHandler(ctx context.Context, s Service, logger log.Logger) http.Handler {
	r := mux.NewRouter()
	e := MakeServerEndpoints(s)
	options := []httptransport.ServerOption{
		httptransport.ServerErrorLogger(logger),
		httptransport.ServerErrorEncoder(encodeError),
	}

	// POST    /profiles/                          adds another profile
	// GET     /profiles/:id                       retrieves the given profile by id
	// PUT     /profiles/:id                       post updated profile information about the profile
	// PATCH   /profiles/:id                       partial updated profile information
	// DELETE  /profiles/:id                       remove the given profile
	// GET     /profiles/:id/addresses/            retrieve addresses associated with the profile
	// GET     /profiles/:id/addresses/:addressID  retrieve a particular profile address
	// POST    /profiles/:id/addresses/            add a new address
	// DELETE  /profiles/:id/addresses/:addressID  remove an address

	r.Methods("POST").Path("/profiles/").Handler(httptransport.NewServer(
		ctx,
		e.PostProfileEndpoint,
		decodePostProfileRequest,
		encodeResponse,
		options...,
	))
	r.Methods("GET").Path("/profiles/{id}").Handler(httptransport.NewServer(
		ctx,
		e.GetProfileEndpoint,
		decodeGetProfileRequest,
		encodeResponse,
		options...,
	))
	r.Methods("PUT").Path("/profiles/{id}").Handler(httptransport.NewServer(
		ctx,
		e.PutProfileEndpoint,
		decodePutProfileRequest,
		encodeResponse,
		options...,
	))
	r.Methods("PATCH").Path("/profiles/{id}").Handler(httptransport.NewServer(
		ctx,
		e.PatchProfileEndpoint,
		decodePatchProfileRequest,
		encodeResponse,
		options...,
	))
	r.Methods("DELETE").Path("/profiles/{id}").Handler(httptransport.NewServer(
		ctx,
		e.DeleteProfileEndpoint,
		decodeDeleteProfileRequest,
		encodeResponse,
		options...,
	))
	r.Methods("GET").Path("/profiles/{id}/addresses/").Handler(httptransport.NewServer(
		ctx,
		e.GetAddressesEndpoint,
		decodeGetAddressesRequest,
		encodeResponse,
		options...,
	))
	r.Methods("GET").Path("/profiles/{id}/addresses/{addressID}").Handler(httptransport.NewServer(
		ctx,
		e.GetAddressEndpoint,
		decodeGetAddressRequest,
		encodeResponse,
		options...,
	))
	r.Methods("POST").Path("/profiles/{id}/addresses/").Handler(httptransport.NewServer(
		ctx,
		e.PostAddressEndpoint,
		decodePostAddressRequest,
		encodeResponse,
		options...,
	))
	r.Methods("DELETE").Path("/profiles/{id}/addresses/{addressID}").Handler(httptransport.NewServer(
		ctx,
		e.DeleteAddressEndpoint,
		decodeDeleteAddressRequest,
		encodeResponse,
		options...,
	))
	return r
}