本文整理匯總了Golang中github.com/go-kit/kit/transport/http.NewServer函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewServer函數的具體用法?Golang NewServer怎麽用?Golang NewServer使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了NewServer函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: main
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))
}
示例2: main
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))
}
示例3: MakeHTTPHandler
// 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
}
示例4: main
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))
}
示例5: main
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))
}
示例6: testServer
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
}
示例7: main
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)
}
}
示例8: main
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))
}
示例9: servermain
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))
}
示例10: MakeSaveAllHandler
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
}
示例11: main
//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))
}
示例12: NewKitHandler
// 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,
)
}
示例13: createHealthCheckRouter
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
}
示例14: createApplicationRouter
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
}
示例15: MakeHTTPHandler
// 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
}