Skip to content
Snippets Groups Projects
Commit 20e3225f authored by Yordan Kinkov's avatar Yordan Kinkov
Browse files

Merge branch '1-goa-skeleton' into 'main'

Service skeleton with health check endpoints

Closes #1

See merge request !1
parents 2336f102 2dc39ba5
No related branches found
No related tags found
1 merge request!1Service skeleton with health check endpoints
Pipeline #49699 passed with stage
in 16 seconds
Showing
with 1016 additions and 1 deletion
vendor/**/* -diff
stages:
- test
before_script:
- ln -s /builds /go/src/code.vereign.com
- cd /go/src/code.vereign.com/${CI_PROJECT_PATH}
lint:
image: golangci/golangci-lint:v1.44.2
stage: test
tags:
- amd64-docker
script:
- golangci-lint --version
- golangci-lint run
unit tests:
image: golang:1.17.7
stage: test
tags:
- amd64-docker
script:
- go version
- go test -race ./... -coverprofile=coverage.out
- go tool cover -func=coverage.out
run:
deadline: 5m
skip-dirs:
- vendor/
- .*fakes/
- .*generated/
skip-files:
- .*generated.go
linters:
disable-all: true
enable:
- megacheck
- govet
- deadcode
- errcheck
- goconst
- gocyclo
- goimports
- revive
- gosec
- ineffassign
- nakedret
- staticcheck
- structcheck
- unconvert
- varcheck
- vet
- vetshadow
- misspell
- staticcheck
# cache
# Cache
Cache exposes HTTP interface for working with Redis.
\ No newline at end of file
package main
import (
"context"
"errors"
"log"
"net/http"
"time"
"github.com/kelseyhightower/envconfig"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
goahttp "goa.design/goa/v3/http"
goa "goa.design/goa/v3/pkg"
"golang.org/x/sync/errgroup"
goahealth "code.vereign.com/gaiax/tsa/cache/gen/health"
goahealthsrv "code.vereign.com/gaiax/tsa/cache/gen/http/health/server"
goaopenapisrv "code.vereign.com/gaiax/tsa/cache/gen/http/openapi/server"
"code.vereign.com/gaiax/tsa/cache/gen/openapi"
"code.vereign.com/gaiax/tsa/cache/internal/config"
"code.vereign.com/gaiax/tsa/cache/internal/service"
"code.vereign.com/gaiax/tsa/cache/internal/service/health"
"code.vereign.com/gaiax/tsa/golib/graceful"
)
var Version = "0.0.0+development"
func main() {
var cfg config.Config
if err := envconfig.Process("", &cfg); err != nil {
log.Fatalf("cannot load configuration: %v", err)
}
logger, err := createLogger(cfg.LogLevel)
if err != nil {
log.Fatalln(err)
}
defer logger.Sync() //nolint:errcheck
logger.Info("start cache service", zap.String("version", Version), zap.String("goa", goa.Version()))
// create services
var (
healthSvc goahealth.Service
)
{
healthSvc = health.New()
}
// create endpoints
var (
healthEndpoints *goahealth.Endpoints
openapiEndpoints *openapi.Endpoints
)
{
healthEndpoints = goahealth.NewEndpoints(healthSvc)
openapiEndpoints = openapi.NewEndpoints(nil)
}
// Provide the transport specific request decoder and response encoder.
// The goa http package has built-in support for JSON, XML and gob.
// Other encodings can be used by providing the corresponding functions,
// see goa.design/implement/encoding.
var (
dec = goahttp.RequestDecoder
enc = goahttp.ResponseEncoder
)
// Build the service HTTP request multiplexer and configure it to serve
// HTTP requests to the service endpoints.
mux := goahttp.NewMuxer()
var (
healthServer *goahealthsrv.Server
openapiServer *goaopenapisrv.Server
)
{
healthServer = goahealthsrv.New(healthEndpoints, mux, dec, enc, nil, errFormatter)
openapiServer = goaopenapisrv.New(openapiEndpoints, mux, dec, enc, nil, errFormatter, nil, nil)
}
// Configure the mux.
goahealthsrv.Mount(mux, healthServer)
goaopenapisrv.Mount(mux, openapiServer)
var handler http.Handler = mux
srv := &http.Server{
Addr: cfg.HTTP.Host + ":" + cfg.HTTP.Port,
Handler: handler,
IdleTimeout: cfg.HTTP.IdleTimeout,
ReadTimeout: cfg.HTTP.ReadTimeout,
WriteTimeout: cfg.HTTP.WriteTimeout,
}
g, ctx := errgroup.WithContext(context.Background())
g.Go(func() error {
if err := graceful.Shutdown(ctx, srv, 20*time.Second); err != nil {
logger.Error("server shutdown error", zap.Error(err))
return err
}
return errors.New("server stopped successfully")
})
if err := g.Wait(); err != nil {
logger.Error("run group stopped", zap.Error(err))
}
logger.Info("bye bye")
}
func createLogger(logLevel string, opts ...zap.Option) (*zap.Logger, error) {
var level = zapcore.InfoLevel
if logLevel != "" {
err := level.UnmarshalText([]byte(logLevel))
if err != nil {
return nil, err
}
}
config := zap.NewProductionConfig()
config.Level = zap.NewAtomicLevelAt(level)
config.DisableStacktrace = true
config.EncoderConfig.TimeKey = "ts"
config.EncoderConfig.EncodeTime = zapcore.RFC3339TimeEncoder
return config.Build(opts...)
}
func errFormatter(e error) goahttp.Statuser {
return service.NewErrorResponse(e)
}
FROM golang:1.17.8-alpine3.15 as builder
ENV GOPRIVATE=code.vereign.com
RUN apk add git
WORKDIR /go/src/code.vereign.com/gaiax/tsa/cache
ADD . .
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-X main.Version=$(git describe --tags --always)" -mod=vendor -o /tmp/cache ./cmd/cache/...
FROM alpine:3.15 as runner
COPY --from=builder /tmp/cache /opt/cache
WORKDIR /opt
CMD ["./cache"]
FROM golang:1.17.8
ENV GO111MODULE=on
ENV GOPRIVATE=code.vereign.com
RUN go install github.com/canthefason/go-watcher/cmd/watcher@v0.2.4
ADD . /go/src/code.vereign.com/gaiax/tsa/cache
WORKDIR /go/src/code.vereign.com/gaiax/tsa/cache
RUN go install -mod=vendor ./cmd/cache/...
EXPOSE 8080
ENTRYPOINT ["sh", "-c", "/go/bin/watcher -run code.vereign.com/gaiax/tsa/cache/cmd/cache -watch code.vereign.com/gaiax/tsa/cache"]
\ No newline at end of file
// nolint:revive
package design
import . "goa.design/goa/v3/dsl"
var _ = API("cache", func() {
Title("Cache Service")
Description("The cache service exposes interface for working with Redis.")
Server("cache", func() {
Description("Cache Server")
Host("development", func() {
Description("Local development server")
URI("http://localhost:8080")
})
})
})
var _ = Service("health", func() {
Description("Health service provides health check endpoints.")
Method("Liveness", func() {
Payload(Empty)
Result(Empty)
HTTP(func() {
GET("/liveness")
Response(StatusOK)
})
})
Method("Readiness", func() {
Payload(Empty)
Result(Empty)
HTTP(func() {
GET("/readiness")
Response(StatusOK)
})
})
})
var _ = Service("openapi", func() {
Description("The openapi service serves the OpenAPI(v3) definition.")
Meta("swagger:generate", "false")
HTTP(func() {
Path("/swagger-ui")
})
Files("/openapi.json", "./gen/http/openapi3.json", func() {
Description("JSON document containing the OpenAPI(v3) service definition")
})
Files("/{*filepath}", "./swagger/")
})
// Code generated by goa v3.7.0, DO NOT EDIT.
//
// health client
//
// Command:
// $ goa gen code.vereign.com/gaiax/tsa/cache/design
package health
import (
"context"
goa "goa.design/goa/v3/pkg"
)
// Client is the "health" service client.
type Client struct {
LivenessEndpoint goa.Endpoint
ReadinessEndpoint goa.Endpoint
}
// NewClient initializes a "health" service client given the endpoints.
func NewClient(liveness, readiness goa.Endpoint) *Client {
return &Client{
LivenessEndpoint: liveness,
ReadinessEndpoint: readiness,
}
}
// Liveness calls the "Liveness" endpoint of the "health" service.
func (c *Client) Liveness(ctx context.Context) (err error) {
_, err = c.LivenessEndpoint(ctx, nil)
return
}
// Readiness calls the "Readiness" endpoint of the "health" service.
func (c *Client) Readiness(ctx context.Context) (err error) {
_, err = c.ReadinessEndpoint(ctx, nil)
return
}
// Code generated by goa v3.7.0, DO NOT EDIT.
//
// health endpoints
//
// Command:
// $ goa gen code.vereign.com/gaiax/tsa/cache/design
package health
import (
"context"
goa "goa.design/goa/v3/pkg"
)
// Endpoints wraps the "health" service endpoints.
type Endpoints struct {
Liveness goa.Endpoint
Readiness goa.Endpoint
}
// NewEndpoints wraps the methods of the "health" service with endpoints.
func NewEndpoints(s Service) *Endpoints {
return &Endpoints{
Liveness: NewLivenessEndpoint(s),
Readiness: NewReadinessEndpoint(s),
}
}
// Use applies the given middleware to all the "health" service endpoints.
func (e *Endpoints) Use(m func(goa.Endpoint) goa.Endpoint) {
e.Liveness = m(e.Liveness)
e.Readiness = m(e.Readiness)
}
// NewLivenessEndpoint returns an endpoint function that calls the method
// "Liveness" of service "health".
func NewLivenessEndpoint(s Service) goa.Endpoint {
return func(ctx context.Context, req interface{}) (interface{}, error) {
return nil, s.Liveness(ctx)
}
}
// NewReadinessEndpoint returns an endpoint function that calls the method
// "Readiness" of service "health".
func NewReadinessEndpoint(s Service) goa.Endpoint {
return func(ctx context.Context, req interface{}) (interface{}, error) {
return nil, s.Readiness(ctx)
}
}
// Code generated by goa v3.7.0, DO NOT EDIT.
//
// health service
//
// Command:
// $ goa gen code.vereign.com/gaiax/tsa/cache/design
package health
import (
"context"
)
// Health service provides health check endpoints.
type Service interface {
// Liveness implements Liveness.
Liveness(context.Context) (err error)
// Readiness implements Readiness.
Readiness(context.Context) (err error)
}
// ServiceName is the name of the service as defined in the design. This is the
// same value that is set in the endpoint request contexts under the ServiceKey
// key.
const ServiceName = "health"
// MethodNames lists the service method names as defined in the design. These
// are the same values that are set in the endpoint request contexts under the
// MethodKey key.
var MethodNames = [2]string{"Liveness", "Readiness"}
// Code generated by goa v3.7.0, DO NOT EDIT.
//
// cache HTTP client CLI support package
//
// Command:
// $ goa gen code.vereign.com/gaiax/tsa/cache/design
package cli
import (
"flag"
"fmt"
"net/http"
"os"
healthc "code.vereign.com/gaiax/tsa/cache/gen/http/health/client"
goahttp "goa.design/goa/v3/http"
goa "goa.design/goa/v3/pkg"
)
// UsageCommands returns the set of commands and sub-commands using the format
//
// command (subcommand1|subcommand2|...)
//
func UsageCommands() string {
return `health (liveness|readiness)
`
}
// UsageExamples produces an example of a valid invocation of the CLI tool.
func UsageExamples() string {
return os.Args[0] + ` health liveness` + "\n" +
""
}
// ParseEndpoint returns the endpoint and payload as specified on the command
// line.
func ParseEndpoint(
scheme, host string,
doer goahttp.Doer,
enc func(*http.Request) goahttp.Encoder,
dec func(*http.Response) goahttp.Decoder,
restore bool,
) (goa.Endpoint, interface{}, error) {
var (
healthFlags = flag.NewFlagSet("health", flag.ContinueOnError)
healthLivenessFlags = flag.NewFlagSet("liveness", flag.ExitOnError)
healthReadinessFlags = flag.NewFlagSet("readiness", flag.ExitOnError)
)
healthFlags.Usage = healthUsage
healthLivenessFlags.Usage = healthLivenessUsage
healthReadinessFlags.Usage = healthReadinessUsage
if err := flag.CommandLine.Parse(os.Args[1:]); err != nil {
return nil, nil, err
}
if flag.NArg() < 2 { // two non flag args are required: SERVICE and ENDPOINT (aka COMMAND)
return nil, nil, fmt.Errorf("not enough arguments")
}
var (
svcn string
svcf *flag.FlagSet
)
{
svcn = flag.Arg(0)
switch svcn {
case "health":
svcf = healthFlags
default:
return nil, nil, fmt.Errorf("unknown service %q", svcn)
}
}
if err := svcf.Parse(flag.Args()[1:]); err != nil {
return nil, nil, err
}
var (
epn string
epf *flag.FlagSet
)
{
epn = svcf.Arg(0)
switch svcn {
case "health":
switch epn {
case "liveness":
epf = healthLivenessFlags
case "readiness":
epf = healthReadinessFlags
}
}
}
if epf == nil {
return nil, nil, fmt.Errorf("unknown %q endpoint %q", svcn, epn)
}
// Parse endpoint flags if any
if svcf.NArg() > 1 {
if err := epf.Parse(svcf.Args()[1:]); err != nil {
return nil, nil, err
}
}
var (
data interface{}
endpoint goa.Endpoint
err error
)
{
switch svcn {
case "health":
c := healthc.NewClient(scheme, host, doer, enc, dec, restore)
switch epn {
case "liveness":
endpoint = c.Liveness()
data = nil
case "readiness":
endpoint = c.Readiness()
data = nil
}
}
}
if err != nil {
return nil, nil, err
}
return endpoint, data, nil
}
// healthUsage displays the usage of the health command and its subcommands.
func healthUsage() {
fmt.Fprintf(os.Stderr, `Health service provides health check endpoints.
Usage:
%[1]s [globalflags] health COMMAND [flags]
COMMAND:
liveness: Liveness implements Liveness.
readiness: Readiness implements Readiness.
Additional help:
%[1]s health COMMAND --help
`, os.Args[0])
}
func healthLivenessUsage() {
fmt.Fprintf(os.Stderr, `%[1]s [flags] health liveness
Liveness implements Liveness.
Example:
%[1]s health liveness
`, os.Args[0])
}
func healthReadinessUsage() {
fmt.Fprintf(os.Stderr, `%[1]s [flags] health readiness
Readiness implements Readiness.
Example:
%[1]s health readiness
`, os.Args[0])
}
// Code generated by goa v3.7.0, DO NOT EDIT.
//
// health HTTP client CLI support package
//
// Command:
// $ goa gen code.vereign.com/gaiax/tsa/cache/design
package client
// Code generated by goa v3.7.0, DO NOT EDIT.
//
// health client HTTP transport
//
// Command:
// $ goa gen code.vereign.com/gaiax/tsa/cache/design
package client
import (
"context"
"net/http"
goahttp "goa.design/goa/v3/http"
goa "goa.design/goa/v3/pkg"
)
// Client lists the health service endpoint HTTP clients.
type Client struct {
// Liveness Doer is the HTTP client used to make requests to the Liveness
// endpoint.
LivenessDoer goahttp.Doer
// Readiness Doer is the HTTP client used to make requests to the Readiness
// endpoint.
ReadinessDoer goahttp.Doer
// RestoreResponseBody controls whether the response bodies are reset after
// decoding so they can be read again.
RestoreResponseBody bool
scheme string
host string
encoder func(*http.Request) goahttp.Encoder
decoder func(*http.Response) goahttp.Decoder
}
// NewClient instantiates HTTP clients for all the health service servers.
func NewClient(
scheme string,
host string,
doer goahttp.Doer,
enc func(*http.Request) goahttp.Encoder,
dec func(*http.Response) goahttp.Decoder,
restoreBody bool,
) *Client {
return &Client{
LivenessDoer: doer,
ReadinessDoer: doer,
RestoreResponseBody: restoreBody,
scheme: scheme,
host: host,
decoder: dec,
encoder: enc,
}
}
// Liveness returns an endpoint that makes HTTP requests to the health service
// Liveness server.
func (c *Client) Liveness() goa.Endpoint {
var (
decodeResponse = DecodeLivenessResponse(c.decoder, c.RestoreResponseBody)
)
return func(ctx context.Context, v interface{}) (interface{}, error) {
req, err := c.BuildLivenessRequest(ctx, v)
if err != nil {
return nil, err
}
resp, err := c.LivenessDoer.Do(req)
if err != nil {
return nil, goahttp.ErrRequestError("health", "Liveness", err)
}
return decodeResponse(resp)
}
}
// Readiness returns an endpoint that makes HTTP requests to the health service
// Readiness server.
func (c *Client) Readiness() goa.Endpoint {
var (
decodeResponse = DecodeReadinessResponse(c.decoder, c.RestoreResponseBody)
)
return func(ctx context.Context, v interface{}) (interface{}, error) {
req, err := c.BuildReadinessRequest(ctx, v)
if err != nil {
return nil, err
}
resp, err := c.ReadinessDoer.Do(req)
if err != nil {
return nil, goahttp.ErrRequestError("health", "Readiness", err)
}
return decodeResponse(resp)
}
}
// Code generated by goa v3.7.0, DO NOT EDIT.
//
// health HTTP client encoders and decoders
//
// Command:
// $ goa gen code.vereign.com/gaiax/tsa/cache/design
package client
import (
"bytes"
"context"
"io/ioutil"
"net/http"
"net/url"
goahttp "goa.design/goa/v3/http"
)
// BuildLivenessRequest instantiates a HTTP request object with method and path
// set to call the "health" service "Liveness" endpoint
func (c *Client) BuildLivenessRequest(ctx context.Context, v interface{}) (*http.Request, error) {
u := &url.URL{Scheme: c.scheme, Host: c.host, Path: LivenessHealthPath()}
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return nil, goahttp.ErrInvalidURL("health", "Liveness", u.String(), err)
}
if ctx != nil {
req = req.WithContext(ctx)
}
return req, nil
}
// DecodeLivenessResponse returns a decoder for responses returned by the
// health Liveness endpoint. restoreBody controls whether the response body
// should be restored after having been read.
func DecodeLivenessResponse(decoder func(*http.Response) goahttp.Decoder, restoreBody bool) func(*http.Response) (interface{}, error) {
return func(resp *http.Response) (interface{}, error) {
if restoreBody {
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
resp.Body = ioutil.NopCloser(bytes.NewBuffer(b))
defer func() {
resp.Body = ioutil.NopCloser(bytes.NewBuffer(b))
}()
} else {
defer resp.Body.Close()
}
switch resp.StatusCode {
case http.StatusOK:
return nil, nil
default:
body, _ := ioutil.ReadAll(resp.Body)
return nil, goahttp.ErrInvalidResponse("health", "Liveness", resp.StatusCode, string(body))
}
}
}
// BuildReadinessRequest instantiates a HTTP request object with method and
// path set to call the "health" service "Readiness" endpoint
func (c *Client) BuildReadinessRequest(ctx context.Context, v interface{}) (*http.Request, error) {
u := &url.URL{Scheme: c.scheme, Host: c.host, Path: ReadinessHealthPath()}
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return nil, goahttp.ErrInvalidURL("health", "Readiness", u.String(), err)
}
if ctx != nil {
req = req.WithContext(ctx)
}
return req, nil
}
// DecodeReadinessResponse returns a decoder for responses returned by the
// health Readiness endpoint. restoreBody controls whether the response body
// should be restored after having been read.
func DecodeReadinessResponse(decoder func(*http.Response) goahttp.Decoder, restoreBody bool) func(*http.Response) (interface{}, error) {
return func(resp *http.Response) (interface{}, error) {
if restoreBody {
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
resp.Body = ioutil.NopCloser(bytes.NewBuffer(b))
defer func() {
resp.Body = ioutil.NopCloser(bytes.NewBuffer(b))
}()
} else {
defer resp.Body.Close()
}
switch resp.StatusCode {
case http.StatusOK:
return nil, nil
default:
body, _ := ioutil.ReadAll(resp.Body)
return nil, goahttp.ErrInvalidResponse("health", "Readiness", resp.StatusCode, string(body))
}
}
}
// Code generated by goa v3.7.0, DO NOT EDIT.
//
// HTTP request path constructors for the health service.
//
// Command:
// $ goa gen code.vereign.com/gaiax/tsa/cache/design
package client
// LivenessHealthPath returns the URL path to the health service Liveness HTTP endpoint.
func LivenessHealthPath() string {
return "/liveness"
}
// ReadinessHealthPath returns the URL path to the health service Readiness HTTP endpoint.
func ReadinessHealthPath() string {
return "/readiness"
}
// Code generated by goa v3.7.0, DO NOT EDIT.
//
// health HTTP client types
//
// Command:
// $ goa gen code.vereign.com/gaiax/tsa/cache/design
package client
// Code generated by goa v3.7.0, DO NOT EDIT.
//
// health HTTP server encoders and decoders
//
// Command:
// $ goa gen code.vereign.com/gaiax/tsa/cache/design
package server
import (
"context"
"net/http"
goahttp "goa.design/goa/v3/http"
)
// EncodeLivenessResponse returns an encoder for responses returned by the
// health Liveness endpoint.
func EncodeLivenessResponse(encoder func(context.Context, http.ResponseWriter) goahttp.Encoder) func(context.Context, http.ResponseWriter, interface{}) error {
return func(ctx context.Context, w http.ResponseWriter, v interface{}) error {
w.WriteHeader(http.StatusOK)
return nil
}
}
// EncodeReadinessResponse returns an encoder for responses returned by the
// health Readiness endpoint.
func EncodeReadinessResponse(encoder func(context.Context, http.ResponseWriter) goahttp.Encoder) func(context.Context, http.ResponseWriter, interface{}) error {
return func(ctx context.Context, w http.ResponseWriter, v interface{}) error {
w.WriteHeader(http.StatusOK)
return nil
}
}
// Code generated by goa v3.7.0, DO NOT EDIT.
//
// HTTP request path constructors for the health service.
//
// Command:
// $ goa gen code.vereign.com/gaiax/tsa/cache/design
package server
// LivenessHealthPath returns the URL path to the health service Liveness HTTP endpoint.
func LivenessHealthPath() string {
return "/liveness"
}
// ReadinessHealthPath returns the URL path to the health service Readiness HTTP endpoint.
func ReadinessHealthPath() string {
return "/readiness"
}
// Code generated by goa v3.7.0, DO NOT EDIT.
//
// health HTTP server
//
// Command:
// $ goa gen code.vereign.com/gaiax/tsa/cache/design
package server
import (
"context"
"net/http"
health "code.vereign.com/gaiax/tsa/cache/gen/health"
goahttp "goa.design/goa/v3/http"
goa "goa.design/goa/v3/pkg"
)
// Server lists the health service endpoint HTTP handlers.
type Server struct {
Mounts []*MountPoint
Liveness http.Handler
Readiness http.Handler
}
// ErrorNamer is an interface implemented by generated error structs that
// exposes the name of the error as defined in the design.
type ErrorNamer interface {
ErrorName() string
}
// MountPoint holds information about the mounted endpoints.
type MountPoint struct {
// Method is the name of the service method served by the mounted HTTP handler.
Method string
// Verb is the HTTP method used to match requests to the mounted handler.
Verb string
// Pattern is the HTTP request path pattern used to match requests to the
// mounted handler.
Pattern string
}
// New instantiates HTTP handlers for all the health service endpoints using
// the provided encoder and decoder. The handlers are mounted on the given mux
// using the HTTP verb and path defined in the design. errhandler is called
// whenever a response fails to be encoded. formatter is used to format errors
// returned by the service methods prior to encoding. Both errhandler and
// formatter are optional and can be nil.
func New(
e *health.Endpoints,
mux goahttp.Muxer,
decoder func(*http.Request) goahttp.Decoder,
encoder func(context.Context, http.ResponseWriter) goahttp.Encoder,
errhandler func(context.Context, http.ResponseWriter, error),
formatter func(err error) goahttp.Statuser,
) *Server {
return &Server{
Mounts: []*MountPoint{
{"Liveness", "GET", "/liveness"},
{"Readiness", "GET", "/readiness"},
},
Liveness: NewLivenessHandler(e.Liveness, mux, decoder, encoder, errhandler, formatter),
Readiness: NewReadinessHandler(e.Readiness, mux, decoder, encoder, errhandler, formatter),
}
}
// Service returns the name of the service served.
func (s *Server) Service() string { return "health" }
// Use wraps the server handlers with the given middleware.
func (s *Server) Use(m func(http.Handler) http.Handler) {
s.Liveness = m(s.Liveness)
s.Readiness = m(s.Readiness)
}
// Mount configures the mux to serve the health endpoints.
func Mount(mux goahttp.Muxer, h *Server) {
MountLivenessHandler(mux, h.Liveness)
MountReadinessHandler(mux, h.Readiness)
}
// Mount configures the mux to serve the health endpoints.
func (s *Server) Mount(mux goahttp.Muxer) {
Mount(mux, s)
}
// MountLivenessHandler configures the mux to serve the "health" service
// "Liveness" endpoint.
func MountLivenessHandler(mux goahttp.Muxer, h http.Handler) {
f, ok := h.(http.HandlerFunc)
if !ok {
f = func(w http.ResponseWriter, r *http.Request) {
h.ServeHTTP(w, r)
}
}
mux.Handle("GET", "/liveness", f)
}
// NewLivenessHandler creates a HTTP handler which loads the HTTP request and
// calls the "health" service "Liveness" endpoint.
func NewLivenessHandler(
endpoint goa.Endpoint,
mux goahttp.Muxer,
decoder func(*http.Request) goahttp.Decoder,
encoder func(context.Context, http.ResponseWriter) goahttp.Encoder,
errhandler func(context.Context, http.ResponseWriter, error),
formatter func(err error) goahttp.Statuser,
) http.Handler {
var (
encodeResponse = EncodeLivenessResponse(encoder)
encodeError = goahttp.ErrorEncoder(encoder, formatter)
)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), goahttp.AcceptTypeKey, r.Header.Get("Accept"))
ctx = context.WithValue(ctx, goa.MethodKey, "Liveness")
ctx = context.WithValue(ctx, goa.ServiceKey, "health")
var err error
res, err := endpoint(ctx, nil)
if err != nil {
if err := encodeError(ctx, w, err); err != nil {
errhandler(ctx, w, err)
}
return
}
if err := encodeResponse(ctx, w, res); err != nil {
errhandler(ctx, w, err)
}
})
}
// MountReadinessHandler configures the mux to serve the "health" service
// "Readiness" endpoint.
func MountReadinessHandler(mux goahttp.Muxer, h http.Handler) {
f, ok := h.(http.HandlerFunc)
if !ok {
f = func(w http.ResponseWriter, r *http.Request) {
h.ServeHTTP(w, r)
}
}
mux.Handle("GET", "/readiness", f)
}
// NewReadinessHandler creates a HTTP handler which loads the HTTP request and
// calls the "health" service "Readiness" endpoint.
func NewReadinessHandler(
endpoint goa.Endpoint,
mux goahttp.Muxer,
decoder func(*http.Request) goahttp.Decoder,
encoder func(context.Context, http.ResponseWriter) goahttp.Encoder,
errhandler func(context.Context, http.ResponseWriter, error),
formatter func(err error) goahttp.Statuser,
) http.Handler {
var (
encodeResponse = EncodeReadinessResponse(encoder)
encodeError = goahttp.ErrorEncoder(encoder, formatter)
)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), goahttp.AcceptTypeKey, r.Header.Get("Accept"))
ctx = context.WithValue(ctx, goa.MethodKey, "Readiness")
ctx = context.WithValue(ctx, goa.ServiceKey, "health")
var err error
res, err := endpoint(ctx, nil)
if err != nil {
if err := encodeError(ctx, w, err); err != nil {
errhandler(ctx, w, err)
}
return
}
if err := encodeResponse(ctx, w, res); err != nil {
errhandler(ctx, w, err)
}
})
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment