kit

package
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 5, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package kit provides a high-level, zero-boilerplate API for rapid prototyping and production microservices.

30-second quickstart

func main() {
    svc := kit.New(":8080")
    svc.Handle("/hello", kit.JSON[HelloReq](func(ctx context.Context, req HelloReq) (any, error) {
        return HelloResp{Message: "Hello, " + req.Name}, nil
    }))
    svc.Run()
}

With middleware

svc := kit.New(":8080",
    kit.WithRateLimit(100),           // 100 req/s
    kit.WithCircuitBreaker(5),        // open after 5 consecutive failures
    kit.WithTimeout(5*time.Second),
    kit.WithRequestID(),              // inject X-Request-ID
    kit.WithLogging(logger),
    kit.WithMetrics(&metrics),
)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func JSON

func JSON[Req any](handler func(ctx context.Context, req Req) (any, error)) http.Handler

JSON is a package-level convenience function that creates a typed JSON http.Handler without needing a Service. It is the recommended way to register typed handlers on a Service, because Go methods cannot have their own type parameters:

svc.Handle("/hello", kit.JSON[HelloReq](func(ctx context.Context, req HelloReq) (any, error) {
    return HelloResp{Message: "Hello, " + req.Name + "!"}, nil
}))

The handler receives a fully decoded value of type Req. Errors are encoded as JSON {"error": "..."} with status 500.

Types

type Option

type Option func(*Service)

Option configures a Service.

func WithCircuitBreaker

func WithCircuitBreaker(consecutiveFailures uint32) Option

WithCircuitBreaker adds a Gobreaker circuit breaker that opens after consecutiveFailures consecutive errors.

func WithGRPC

func WithGRPC(addr string, opts ...grpc.ServerOption) Option

WithGRPC enables a gRPC server on the given address (e.g. ":8081"). Call GRPCServer() to register your proto services before calling Run/Start.

Example:

svc := kit.New(":8080", kit.WithGRPC(":8081"))
pb.RegisterGreeterServer(svc.GRPCServer(), &myGreeter{})
svc.Run()

func WithLogging

func WithLogging(logger *kitlog.Logger) Option

WithLogging adds structured request logging.

func WithMetrics

func WithMetrics(m *endpoint.Metrics) Option

WithMetrics attaches a Metrics collector. The /health endpoint will include the request count when this option is set.

func WithRateLimit

func WithRateLimit(rps float64) Option

WithRateLimit adds a token-bucket rate limiter (rps = requests per second).

func WithRequestID

func WithRequestID() Option

WithRequestID injects a unique request ID into the context and response headers. The ID is taken from X-Request-ID if present, otherwise generated.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout adds a per-request context deadline.

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service is a ready-to-run HTTP + gRPC microservice. Create one with New, register handlers with Handle/GRPC, then call Run.

func New

func New(addr string, opts ...Option) *Service

New creates a Service listening on addr (e.g. ":8080").

func (*Service) GRPCServer

func (s *Service) GRPCServer() *grpc.Server

GRPCServer returns the underlying *grpc.Server so callers can register proto services. It is created lazily on first call. Panics if WithGRPC was not set.

Example:

pb.RegisterGreeterServer(svc.GRPCServer(), &myGreeter{})

func (*Service) Handle

func (s *Service) Handle(pattern string, handler http.Handler)

Handle registers an http.Handler for the given pattern. Service-level middleware (metrics, timeout, circuit breaker, etc.) is applied by wrapping the handler as an endpoint so the full middleware chain executes.

func (*Service) HandleFunc

func (s *Service) HandleFunc(pattern string, fn http.HandlerFunc)

HandleFunc registers a plain http.HandlerFunc.

func (*Service) Run

func (s *Service) Run()

Run starts the HTTP server (and gRPC server if WithGRPC was set) and blocks until SIGINT/SIGTERM. It performs a graceful shutdown with a 10-second deadline.

func (*Service) ServeHTTP

func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler, allowing Service to be used directly with httptest.NewServer or http.ListenAndServe.

func (*Service) Shutdown

func (s *Service) Shutdown(ctx context.Context) error

Shutdown gracefully stops the HTTP server (and gRPC server if running). Useful in tests.

func (*Service) Start

func (s *Service) Start()

Start starts the HTTP server (and gRPC server if WithGRPC was set) in the background and returns immediately. Use this in tests or when you need to manage the lifecycle yourself. Call Shutdown to stop both servers.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL