summer

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Feb 16, 2023 License: MIT Imports: 17 Imported by: 1

README

summer

A Minimalist Mesh-Native Microservice Framework for Golang

Core Concept

By using generics, summer allows you to use the basic summer.Context, or create your own Context type, without changing programming paradigm.

Features

  • Support opentelemetry-go
    • Support standard OTEL_ environment variables
    • Using zipkin as default exporter
    • Support TraceContext, Baggage and B3 propagation
    • Support otelhttp instrument
  • Support prometheus/promhttp
    • Expose at /debug/metrics
  • Support Readiness Check
    • Expose at /debug/ready
    • Component readiness registration with App#Check()
  • Support Liveness Check
    • Expose at /debug/alive
    • Cascade Liveness Check failure from continuous Readiness Check failure
  • Support debug/pprof
    • Expose at /debug/pprof
  • Bind request data
    • Unmarshal header, query, json body and form body into any structure with json tag

Setup Tracing

OpenTelemetry setup is left to end-user

Example:

package summer

import (
	"github.com/guoyk93/rg"
	"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
	"go.opentelemetry.io/contrib/propagators/b3"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/exporters/zipkin"
	"go.opentelemetry.io/otel/propagation"
	sdktrace "go.opentelemetry.io/otel/sdk/trace"
	"net/http"
)

// BootTracing setup OpenTelemetry tracing best practice
func BootTracing() {
	otel.SetTracerProvider(sdktrace.NewTracerProvider(
		sdktrace.WithBatcher(rg.Must(zipkin.New(""))),
	))
	otel.SetTextMapPropagator(
		propagation.NewCompositeTextMapPropagator(
			propagation.TraceContext{},
			propagation.Baggage{},
			b3.New(b3.WithInjectEncoding(b3.B3MultipleHeader|b3.B3SingleHeader)),
		),
	)
	// re-initialize otelhttp.DefaultClient and http.DefaultClient
	otelhttp.DefaultClient = &http.Client{
		Transport: otelhttp.NewTransport(http.DefaultTransport),
	}
	http.DefaultClient = otelhttp.DefaultClient
}

Donation

See https://guoyk.xyz/donation

Credits

Guo Y.K., MIT License

Documentation

Index

Constants

View Source
const (
	ContentTypeApplicationJSON = "application/json"
	ContentTypeTextPlain       = "text/plain"
	ContentTypeFormURLEncoded  = "application/x-www-form-urlencoded"

	ContentTypeApplicationJSONUTF8 = "application/json; charset=utf-8"
	ContentTypeTextPlainUTF8       = "text/plain; charset=utf-8"
	ContentTypeFormURLEncodedUTF8  = "application/x-www-form-urlencoded; charset=utf-8"

	DefaultReadinessPath = "/debug/ready"
	DefaultLivenessPath  = "/debug/alive"
	DefaultMetricsPath   = "/debug/metrics"
)
View Source
const (
	HaltExtraKeyMessage = "message"
)

Variables

This section is empty.

Functions

func Bind

func Bind[T any](c Context) (o T)

Bind a generic version of [Context.Bind]

example:

	func actionValidate(c summer.Context) {
		args := summer.Bind[struct {
       		Tenant       string `json:"header_x_tenant"`
			Username     string `json:"username"`
			Age 		 int    `json:"age,string"`
		}](c)
        _ = args.Tenant
        _ = args.Username
        _ = args.Age
	}

func BodyFromError

func BodyFromError(err error) (m map[string]any)

BodyFromError extract extras from previous created [HaltError]

func Halt

func Halt(err error, opts ...HaltOption)

Halt panic with NewHaltError

func HaltString

func HaltString(s string, opts ...HaltOption)

HaltString panic with NewHaltError and errors.New

func NewHaltError

func NewHaltError(err error, opts ...HaltOption) error

NewHaltError create a new [HaltError]

func StatusCodeFromError

func StatusCodeFromError(err error) int

StatusCodeFromError get status code from previous created [HaltError]

Types

type App

type App[T Context] interface {
	http.Handler

	// CheckFunc register a checker function with given name
	//
	// Invoking '/debug/ready' will evaluate all registered checker functions
	CheckFunc(name string, fn CheckerFunc)

	// HandleFunc register an action function with given path pattern
	//
	// This function is similar with [http.ServeMux.HandleFunc]
	HandleFunc(pattern string, fn HandlerFunc[T])
}

App the main interface of summer

func New

func New[T Context](cf ContextFactory[T], opts ...Option) App[T]

New create an App with a custom ContextFactory and additional Option

type BasicApp

type BasicApp = App[Context]

BasicApp basic app is an App using vanilla Context

func Basic

func Basic(opts ...Option) BasicApp

Basic create an App with vanilla Context and additional Option

type CheckerFunc

type CheckerFunc func(ctx context.Context) (err error)

CheckerFunc health check function, see [App.Check]

type Context

type Context interface {
	// Context extend the [context.Context] interface by proxying to [http.Request.Context]
	context.Context

	// Req returns the underlying *http.Request
	Req() *http.Request
	// Res returns the underlying http.ResponseWriter
	Res() http.ResponseWriter

	// Bind unmarshal the request data into any struct with json tags
	//
	// HTTP header is prefixed with "header_"
	//
	// HTTP query is prefixed with "query_"
	//
	// both JSON and Form are supported
	Bind(data interface{})

	// Code set the response code, can be called multiple times
	Code(code int)

	// Body set the response body with content type, can be called multiple times
	Body(contentType string, buf []byte)

	// Text set the response body to plain text
	Text(s string)

	// JSON set the response body to json
	JSON(data interface{})

	// Perform actually perform the response
	// it is suggested to use in defer, recover() is included to recover from any panics
	Perform()
}

Context the most basic context of a incoming request and corresponding response

func BasicContext

func BasicContext(rw http.ResponseWriter, req *http.Request) Context

BasicContext context factory creating a basic Context implementation

type ContextFactory

type ContextFactory[T Context] func(rw http.ResponseWriter, req *http.Request) T

ContextFactory factory function for creating an extended Context

type HaltOption

type HaltOption func(h *haltError)

HaltOption configuration function for [HaltError]

func HaltWithBadRequest added in v1.0.1

func HaltWithBadRequest() HaltOption

HaltWithBadRequest alias to HaltWithStatusCode with http.StatusBadRequest

func HaltWithExtra

func HaltWithExtra(k string, v any) HaltOption

HaltWithExtra a HaltOption setting extras with a key-value

func HaltWithExtras

func HaltWithExtras(m map[string]any) HaltOption

HaltWithExtras a HaltOption setting extras with key-values

func HaltWithMessage

func HaltWithMessage(m string) HaltOption

HaltWithMessage a HaltOption overriding message key

func HaltWithStatusCode

func HaltWithStatusCode(code int) HaltOption

HaltWithStatusCode a HaltOption setting status code

type HandlerFunc

type HandlerFunc[T Context] func(ctx T)

HandlerFunc handler func with Context as argument

type Option

type Option func(opts *options)

Option a function configuring App

func WithConcurrency

func WithConcurrency(c int) Option

WithConcurrency set maximum concurrent requests of App.

A value <= 0 means unlimited

func WithLivenessPath added in v1.0.2

func WithLivenessPath(s string) Option

WithLivenessPath set liveness path

func WithMetricsPath added in v1.0.2

func WithMetricsPath(s string) Option

WithMetricsPath set metrics path

func WithReadinessCascade

func WithReadinessCascade(rc int) Option

WithReadinessCascade set maximum continuous failed Readiness Checks after which Liveness CheckFunc start to fail.

Failing Liveness Checks could trigger a Pod restart.

A value <= 0 means disabled

func WithReadinessPath added in v1.0.2

func WithReadinessPath(s string) Option

WithReadinessPath set readiness check path

Jump to

Keyboard shortcuts

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