func main() { router := mux.NewRouter() ctx := context.Background() svc := yell.YellingService{} yellHandler := httptransport.NewServer( ctx, yell.MakeYellEndpoint(svc), yell.DecodeYellRequest, yell.EncodeResponse, ) composeHandler := httptransport.NewServer( ctx, compose.MakeComposeEndpoint(svc), compose.DecodeComposeRequest, compose.EncodeResponse, ) router.HandleFunc("/", RootHandler) router.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(*staticPath)))) http.Handle("/yell", yellHandler) http.Handle("/compose", composeHandler) go http.ListenAndServe(":8080", nil) go log.Fatal(http.ListenAndServe(":8081", router)) }
func main() { var ( listen = flag.String("listen", ":8080", "HTTP listen address") proxy = flag.String("proxy", "", "Optional comma-separated list of URLs to proxy uppercase requests") ) flag.Parse() var logger log.Logger logger = log.NewLogfmtLogger(os.Stderr) logger = log.NewContext(logger).With("listen", *listen).With("caller", log.DefaultCaller) ctx := context.Background() fieldKeys := []string{"method", "error"} requestCount := kitprometheus.NewCounter(stdprometheus.CounterOpts{ Namespace: "my_group", Subsystem: "string_service", Name: "request_count", Help: "Number of requests received.", }, fieldKeys) requestLatency := metrics.NewTimeHistogram(time.Microsecond, kitprometheus.NewSummary(stdprometheus.SummaryOpts{ Namespace: "my_group", Subsystem: "string_service", Name: "request_latency_microseconds", Help: "Total duration of requests in microseconds.", }, fieldKeys)) countResult := kitprometheus.NewSummary(stdprometheus.SummaryOpts{ Namespace: "my_group", Subsystem: "string_service", Name: "count_result", Help: "The result of each count method.", }, []string{}) var svc StringService svc = stringService{} svc = proxyingMiddleware(*proxy, ctx, logger)(svc) svc = loggingMiddleware(logger)(svc) svc = instrumentingMiddleware(requestCount, requestLatency, countResult)(svc) uppercaseHandler := httptransport.NewServer( ctx, makeUppercaseEndpoint(svc), decodeUppercaseRequest, encodeResponse, ) countHandler := httptransport.NewServer( ctx, makeCountEndpoint(svc), decodeCountRequest, encodeResponse, ) http.Handle("/uppercase", uppercaseHandler) http.Handle("/count", countHandler) http.Handle("/metrics", stdprometheus.Handler()) logger.Log("msg", "HTTP", "addr", *listen) logger.Log("err", http.ListenAndServe(*listen, nil)) }
// 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 main() { ctx := context.Background() logger := log.NewLogfmtLogger(os.Stderr) //Define metrics to be collected for this service fieldKeys := []string{"method", "error"} requestCount := kitprometheus.NewCounter(stdprometheus.CounterOpts{ Namespace: "my_group", Subsystem: "string_service", Name: "request_count", Help: "Number of requests received.", }, fieldKeys) requestLatency := metrics.NewTimeHistogram(time.Microsecond, kitprometheus.NewSummary(stdprometheus.SummaryOpts{ Namespace: "my_group", Subsystem: "string_service", Name: "request_latency_microseconds", Help: "Total duration of requests in Microseconds.", }, fieldKeys)) countResult := kitprometheus.NewSummary(stdprometheus.SummaryOpts{ Namespace: "my_group", Subsystem: "string_service", Name: "count_result", Help: "The result of eac count method", }, []string{}) //Declare the string service var svc StringService svc = stringService{} svc = loggingMiddleware{logger, svc} svc = instrumentingMiddleware{requestCount, requestLatency, countResult, svc} //Declare and define a http server that exposes the string service to clients via httptransport uppercaseHandler := httptransport.NewServer( ctx, makeUppercaseEndpoint(svc), decodeUppercaseRequest, encodeResponse, ) countHandler := httptransport.NewServer( ctx, makeCountEndpoint(svc), decodeCountRequest, encodeResponse, ) //Define the content routes http.Handle("/uppercase", uppercaseHandler) http.Handle("/count", countHandler) http.Handle("/metrics", stdprometheus.Handler()) logger.Log("msg", "HTTP", "addr", ":8080") logger.Log("err", http.ListenAndServe(":8080", nil)) }
func main() { ctx := context.Background() logger := log.NewLogfmtLogger(os.Stderr) fieldKeys := []string{"method", "error"} requestCount := kitprometheus.NewCounterFrom(stdprometheus.CounterOpts{ Namespace: "my_group", Subsystem: "string_service", Name: "request_count", Help: "Number of requests received.", }, fieldKeys) requestLatency := kitprometheus.NewSummaryFrom(stdprometheus.SummaryOpts{ Namespace: "my_group", Subsystem: "string_service", Name: "request_latency_microseconds", Help: "Total duration of requests in microseconds.", }, fieldKeys) countResult := kitprometheus.NewSummaryFrom(stdprometheus.SummaryOpts{ Namespace: "my_group", Subsystem: "string_service", Name: "count_result", Help: "The result of each count method.", }, []string{}) // no fields here var svc StringService svc = stringService{} svc = loggingMiddleware{logger, svc} svc = instrumentingMiddleware{requestCount, requestLatency, countResult, svc} uppercaseHandler := httptransport.NewServer( ctx, makeUppercaseEndpoint(svc), decodeUppercaseRequest, encodeResponse, ) countHandler := httptransport.NewServer( ctx, makeCountEndpoint(svc), decodeCountRequest, encodeResponse, ) http.Handle("/uppercase", uppercaseHandler) http.Handle("/count", countHandler) http.Handle("/metrics", stdprometheus.Handler()) logger.Log("msg", "HTTP", "addr", ":8080") logger.Log("err", http.ListenAndServe(":8080", nil)) }
func testServer(t *testing.T) (cancel, step func(), resp <-chan *http.Response) { var ( ctx, cancelfn = context.WithCancel(context.Background()) stepch = make(chan bool) endpoint = func(context.Context, interface{}) (interface{}, error) { <-stepch; return struct{}{}, nil } response = make(chan *http.Response) handler = httptransport.NewServer( ctx, endpoint, func(*http.Request) (interface{}, error) { return struct{}{}, nil }, func(http.ResponseWriter, interface{}) error { return nil }, httptransport.ServerBefore(func(ctx context.Context, r *http.Request) context.Context { return ctx }), httptransport.ServerAfter(func(ctx context.Context, w http.ResponseWriter) { return }), ) ) go func() { server := httptest.NewServer(handler) defer server.Close() resp, err := http.Get(server.URL) if err != nil { t.Error(err) return } response <- resp }() return cancelfn, func() { stepch <- true }, response }
func main() { logger := log.NewLogfmtLogger(os.Stdout) ctx := context.Background() c := &countService{} var svc endpoint.Endpoint svc = makeAddEndpoint(c) limit := ratelimit.NewBucket(2*time.Second, 1) svc = kitratelimit.NewTokenBucketLimiter(limit)(svc) requestCount := expvar.NewCounter("request.count") svc = metricsMiddleware(requestCount)(svc) svc = loggingMiddlware(logger)(svc) addHandler := httptransport.NewServer( ctx, svc, decodeAddRequest, encodeResponse, httptransport.ServerBefore(beforeIDExtractor, beforePATHExtractor), ) http.Handle("/add", addHandler) port := os.Getenv("PORT") logger.Log("listening on", port) if err := http.ListenAndServe(":"+port, nil); err != nil { logger.Log("listen.error", err) } }
func main() { // setup a logger logger = log.NewLogfmtLogger(os.Stderr) logger = log.NewContext(logger).With("svc", "sensor").With("caller", log.DefaultCaller) // setup rethinkdb session session := getSession() // build the context ctx := context.Background() // new service svc := NewSensorService(session) // wrap it in the logging middleware svc = loggingMiddleware(logger)(svc) // bind the service to HTTP with the context // with it's matching encoder/decoder recordHandler := httptransport.NewServer( ctx, makeRecordEndpoint(svc), decodeRecordRequest, encodeResponse, ) // assign an endpoint route http.Handle("/sensor/record", recordHandler) // bind the listener logger.Log("msg", "HTTP", "addr", ":5000") logger.Log("err", http.ListenAndServe(":5000", nil)) }
func servermain() { lib, nerr := glick.New(nil) if nerr != nil { panic(nerr) } if err := lib.RegAPI("api", uppercaseRequest{}, func() interface{} { return uppercaseResponse{} }, time.Second); err != nil { panic(err) } if err := lib.RegPlugin("api", "lc", func(ctx context.Context, in interface{}) (interface{}, error) { return uppercaseResponse{ V: strings.ToLower(in.(uppercaseRequest).S), }, nil }, nil); err != nil { panic(err) } ctx := context.Background() svc := stringService{} lowercaseHandler := httptransport.NewServer( ctx, glkit.MakeEndpoint(lib, "api", "lc"), decodeUppercaseRequest, encodeResponse, ) uppercaseHandler := httptransport.NewServer( ctx, makeUppercaseEndpoint(svc), decodeUppercaseRequest, encodeResponse, ) countHandler := httptransport.NewServer( ctx, makeCountEndpoint(svc), decodeCountRequest, encodeResponse, ) http.Handle("/uppercase", uppercaseHandler) http.Handle("/lowercase", lowercaseHandler) http.Handle("/count", countHandler) log.Fatal(http.ListenAndServe("localhost:8080", nil)) }
func MakeSaveAllHandler(ctx context.Context) http.Handler { var saveallendpoint = MakeSaveAllEndpoint() saveallendpoint = authservice.RestrictedAccessMiddleware()(saveallendpoint) var typedrequest = new(http_req_res.ReqSaveAll) var saveallhandler = httptransport.NewServer(ctx, saveallendpoint, http_req_res.DecodeRequest(typedrequest), http_req_res.EncodeResponse) handler := http_req_res.CORS.Handler(saveallhandler) return handler }
//Main func main() { ctx := context.Background() svc := stringService{} uppercaseHandler := httptransport.NewServer(ctx, makeUppercaseEndpoint(svc), decodeUppercaseRequest, encodeResponse) countHandler := httptransport.NewServer( ctx, makeCountEndpoint(svc), decodeCountRequest, encodeResponse) http.Handle("/uppercase", uppercaseHandler) http.Handle("/count", countHandler) log.Fatal(http.ListenAndServe(":8080", nil)) }
// NewKitHandler create new kit handler func NewKitHandler(ctx context.Context, ep *Endpoint) *kithttp.Server { return kithttp.NewServer( ctx, func(ctx context.Context, request interface{}) (interface{}, error) { return ep.Response(request.(*Request)) }, func(r *http.Request) (request interface{}, err error) { return service.KitJSONDecodeFunc(r, NewRequest()) }, service.KitJSONEncodeFunc, ) }
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.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 }
// 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 }
func Register() { ctx := context.Background() fieldKeys := []string{"method", "error"} requestCount := gkprometheus.NewCounter(prometheus.CounterOpts{ Namespace: "blueplanet", Subsystem: "bp2_service", Name: "request_count", Help: "Number of requests received.", }, fieldKeys) requestLatency := gkmetrics.NewTimeHistogram(time.Microsecond, gkprometheus.NewSummary(prometheus.SummaryOpts{ Namespace: "blueplanet", Subsystem: "bp2_service", Name: "request_latency_microseconds", Help: "Total duraction of the requests in microseconds.", }, fieldKeys)) var svc StringService svc = stringService{} svc = instrumentingMiddleware{requestCount, requestLatency, svc} uppercaseHandler := gkhttptransport.NewServer( ctx, makeUppercaseEndpoint(svc), decodeUppercaseRequest, encodeResponse, ) countHandler := gkhttptransport.NewServer( ctx, makeCountEndpoint(svc), decodeCountRequest, encodeResponse, ) http.Handle("/string/uppercase", uppercaseHandler) http.Handle("/string/count", countHandler) http.Handle("/string/metrics", prometheus.Handler()) }
func TestServerBadEncode(t *testing.T) { handler := httptransport.NewServer( context.Background(), func(context.Context, interface{}) (interface{}, error) { return struct{}{}, nil }, func(*http.Request) (interface{}, error) { return struct{}{}, nil }, func(http.ResponseWriter, interface{}) error { return errors.New("dang") }, ) server := httptest.NewServer(handler) defer server.Close() resp, _ := http.Get(server.URL) if want, have := http.StatusInternalServerError, resp.StatusCode; want != have { t.Errorf("want %d, have %d", want, have) } }
// 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...) }
func main() { ctx := context.Background() as := ageService{} ageHandler := httptransport.NewServer( ctx, makeCalculateAgeEndpoint(as), decodeAgeRequest, encodeResponse, ) http.Handle("/age", ageHandler) log.Fatal(http.ListenAndServe(":8001", nil)) }
func main() { ctx := context.Background() svc := simpleStringManipulatingMicroservice{} uppercaseHandler := httptransport.NewServer( ctx, makeUppercaseEndpoint(svc), decodeUppercaseRequest, encodeResponse, ) http.Handle("/uppercase", uppercaseHandler) log.Fatal(http.ListenAndServe(":8080", nil)) }
func main() { ctx := context.Background() database, err := bolt.Open("gnolly.db", 0600, nil) defer database.Close() if err != nil { panic(err) } _ = database.Update(func(tx *bolt.Tx) error { tx.CreateBucketIfNotExists([]byte("main")) return nil }) svc := gnolly{database} getHandler := httptransport.NewServer( ctx, makeGetEndpoint(&svc), decodeGetRequest, encodeResponse, ) putHandler := httptransport.NewServer( ctx, makePutEndpoint(&svc), decodePutRequest, encodeResponse, ) http.Handle("/get", getHandler) http.Handle("/put", putHandler) log.Fatal(http.ListenAndServe(":8080", nil)) }
func init() { ctx := context.Background() svc := echoService{} echoHandler := httptransport.NewServer( ctx, makeEchoEndpoint(svc), decodeEchoRequest, encodeResponse, ) http.HandleFunc("/", hello) http.Handle("/echo", echoHandler) // log.Fatal(http.ListenAndServe(":8080", nil)) }
func main() { ctx := context.Background() svc := exService{} handler := httptransport.NewServer( ctx, makeEndpoint(svc), func(r *http.Request) (request interface{}, err error) { return nil, nil }, func(w http.ResponseWriter, response interface{}) error { return json.NewEncoder(w).Encode(response) }, ) http.Handle("/", handler) log.Fatal(http.ListenAndServe(":8082", nil)) }
func main() { ctx := context.Background() svc := service{} handler := httptransport.NewServer( ctx, makeEndpoint(svc), decodeRequest, encodeResponse, ) http.Handle("/api/v1/exec", handler) http.Handle("/api/v0.1/exec", handler) http.Handle("/", handler) port := strconv.Itoa(int(*flags.Port)) log.Fatal(http.ListenAndServe(":"+port, nil)) }
func main() { var ( listen = flag.String("listen", ":8080", "HTTP listen address") // proxy = flag.String("proxy", "", "Optional comma-separated list of URLs to proxy uppercase requests") ) flag.Parse() var logger log.Logger logger = log.NewLogfmtLogger(os.Stderr) logger = log.NewContext(logger).With("listen", *listen).With("caller", log.DefaultCaller) loglevel := levels.New(logger) ctx := context.Background() redisURL := os.Getenv("REDIS_URL") redisPassword := os.Getenv("REDIS_PASSWORD") if redisURL == "" || redisPassword == "" { _ = loglevel.Crit("err", "missing REDIS connection information") return } infra, err := BuildInfrastructure(InfrastructureOptions{ DialURL: os.Getenv("REDIS_URL"), DialOption: []redis.DialOption{redis.DialPassword(redisPassword)}, }) if err != nil { _ = loglevel.Crit("err", fmt.Sprintf("Infrastructure error: %v", err)) return } defer infra.conn.Close() var svc CacheService svc = cacheService{} svc = loggingMiddleware(logger)(svc) cacheHandler := httptransport.NewServer( ctx, makeCacheEndpoint(svc), decodeCacheRequest, encodeResponse, ) http.Handle("/cache", cacheHandler) _ = logger.Log("msg", "HTTP", "addr", *listen) _ = logger.Log("err", http.ListenAndServe(*listen, nil)) }
func main() { ctx := context.Background() logger := log.NewLogfmtLogger(os.Stderr) var srv StringService srv = stringService{} countHandler := httptransport.NewServer( ctx, makeCountEndpoint(srv), decodeCountRequest, encodeResponse, ) http.Handle("/count", countHandler) logger.Log("msg", "HTTP", "addr", ":8080") logger.Log("err", http.ListenAndServe(":8080", nil)) }
func main() { backgroundContext := context.Background() logger := log.NewJSONLogger(os.Stderr) var service PingPongService service = pingPongService{} service = LoggingMiddleware{logger, service} pongHandler := httpTransport.NewServer( backgroundContext, MakePingEndpoint(service), DecodePingRequest, EncodeResponse, ) http.Handle("/ping", pongHandler) logger.Log("msg", "HTTP", "addr", ":10002") logger.Log("err", http.ListenAndServe(":10002", nil)) }
// 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 }
// 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 }
func main() { logger := *log.New(os.Stdout, "add service: ", log.Ldate|log.Ltime|log.Lmicroseconds|log.Llongfile) ctx := context.Background() svc := service.AddServiceLoggingMiddleware{ Logger: logger, Service: service.AddService{}, } addEndpoint := service.AddServiceEndpointLoggingMiddleware(logger)(service.MakeAddEndpoint(svc)) addHandler := httptransport.NewServer( ctx, addEndpoint, service.DecodeAddRequest, service.EncodeAddResponse, ) http.Handle("/add", addHandler) log.Fatal(http.ListenAndServe(":8000", nil)) }