rp

package module
v0.0.0-...-131c832 Latest Latest
Warning

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

Go to latest
Published: Aug 14, 2023 License: MIT Imports: 8 Imported by: 0

README

rp

rp, the “request pipeline” framework, makes server endpoints with multiple execution steps easier to build, maintain, and optimize. It is built with Gin, Go's top web framework.

It works by wrapping execution steps of any arbitrary code into stages that can be linked together into execution chains. Chains, in turn, can be executed, in sequence or in parallel (concurrently), with a logger that automatically tracks each stage’s success or failure along with performance metrics like latency.

Check out the tutorial for more.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrNotFound = errors.New("not found")

Functions

func AddRoute

func AddRoute(engine *gin.Engine, route *Route)

func CtxOutStr

func CtxOutStr(ctxOutputs ...string) string

CtxOutStr generates a string such as ` => ["ctxOutVar1"], ["ctxOutVar2"]` from the inputs CtxOutStr("ctxOutVar1", "ctxOutVar2")

func FuncStr

func FuncStr(name string, ctxDependencies ...string) string

FuncStr generates a string such as `my_stage_name(["ctxVar1"], ["ctxVar2"])` from the inputs FuncStr("my_stage_name", "ctxVar1", "ctxVar2")

func MakeGinHandlerFunc

func MakeGinHandlerFunc(ch *Chain, lgr Logger) gin.HandlerFunc

func StageName

func StageName(usesInParam bool, name string, ctxDependencies []string, ctxOutputs []string, returnsAValue bool) string

StageName generates a string such as ` => my_stage_name(["ctxVar"]) => ["newCtxVar"]` from the inputs StageName(true, "my_stage_name", []string{"ctxVar"}, []string{"newCtxVar"}, false)

Types

type Chain

type Chain struct {
	First *Stage
	Last  *Stage
}

func First

func First(s *Stage) *Chain

Pipelines should be defined by sending the first Stage in to the First function and then each following Stage into the Then function. The pipeline definition should read like:

pipeline := First(stage0).Then(stage1).Then(stage2) ...

or alternatively:

pipeline := First(
    stage0).Then(
    stage1).Then(
    stage2) ...

func InParallel

func InParallel(chains ...*Chain) *Chain

func InSequence

func InSequence(chains ...*Chain) *Chain

InSequence concatenates together multiple chains defined by the above First+Then method.

func MakeChain

func MakeChain(stages ...*Stage) *Chain

Alternatively, MakeChain can build a chain from a slice of stages.

func (*Chain) Catch

func (ch *Chain) Catch(Code int, Message string) *Chain

Catch can be used to optionally override a stage's E function like:

pipeline := First(
    stage0).Then(
    stage1).Catch(http.StatusBadRequest, "stage1 failed").Then(
    stage2) ...

func (*Chain) CatchError

func (ch *Chain) CatchError(E func(err error) *StageError) *Chain

func (*Chain) Then

func (ch *Chain) Then(n *Stage) *Chain

type ChainExecutionError

type ChainExecutionError struct {
	StageError *StageError
}

func (ChainExecutionError) Error

func (e ChainExecutionError) Error() string

type DefaultLogger

type DefaultLogger struct {
	Logger
}

func (DefaultLogger) LogMessage

func (l DefaultLogger) LogMessage(msg string)

func (DefaultLogger) LogStageComplete

func (l DefaultLogger) LogStageComplete(success bool, elapsed time.Duration, print string, out any)

func (DefaultLogger) LogStageError

func (l DefaultLogger) LogStageError(e *StageError)

func (DefaultLogger) LogStageStart

func (l DefaultLogger) LogStageStart(print string, in any)

type H

type H map[string]any

type JSONResponse

type JSONResponse struct {
	Code int // HTTP status code
	Obj  any // JSON response data
}

TODO: Replace the Response and StageError types with this single type

type Logger

type Logger interface {
	LogMessage(msg string)
	LogStageStart(print string, in any)
	LogStageComplete(success bool, elapsed time.Duration, print string, out any)
	LogStageError(e *StageError)
}

type Response

type Response struct {
	Code int // HTTP status code
	Obj  any // JSON response data
}

type Route

type Route struct {
	HttpMethod   string
	RelativePath string
	Pipe         *Chain
	Logger       Logger
}

func (*Route) Handler

func (r *Route) Handler() gin.HandlerFunc

func (*Route) Run

func (r *Route) Run(c *gin.Context)

Run runs the route's Pipe and sets the network response based on the run results.

type Stage

type Stage struct {
	P func() string                                // Printed name of the stage, for logging
	F func(any, *gin.Context, Logger) (any, error) // Function to execute. Optional logger for stages that nest chains.
	E func(error) *StageError                      // Network error to return for F's error
	// contains filtered or unexported fields
}

Stage is a step in a request pipeline. Stages are connected together as double-linked lists by n and l. When a pipeline is run, it executes each Stage's F function. The input to F is the output of the last Stage plus the request's context. The output of F is, in turn, passed into the next Stage. When F returns an error, it is passed in to the E function, which generates the HTTP status code and JSON response data that should be returned in the network response. The last Stage of a pipeline should return a *Response as the output of F. When a stage completes, P() will be logged to the console with the results of the stage.

func Bind

func Bind(obj any) *Stage

func CtxGet

func CtxGet(key string) *Stage

func CtxSet

func CtxSet(key string) *Stage

func FieldValue

func FieldValue(key string) *Stage

func If

func If(cond func(any, *gin.Context) bool, then *Chain, els *Chain) *Stage

func QueryParam

func QueryParam(key string) *Stage

func S

func S(name string, f func(any, *gin.Context, Logger) (any, error)) *Stage

S creates a generic stage that executes the given function. E's default code is http.StatusBadRequest since that is common.

func ToObjectID

func ToObjectID() *Stage

func ToTime

func ToTime(layout string) *Stage

ToTime - Converts in to time.Time for the UTC timezone. in must be a string matching the given layout. It is equivalent to calling ToTimeInLocation with ctxTimezoneName = "".

func ToTimeInLocation

func ToTimeInLocation(ctxTimezoneName string, layout string) *Stage

ToTimeInLocation - Converts in to time.Time. in must be a string. It will be parsed per the given timezone and layout. If ctxTimezoneName is "" or its value has not been set in the context, UTC will be used.

func URLParam

func URLParam(key string) *Stage

func (*Stage) Chain

func (s *Stage) Chain() *Chain

func (*Stage) Execute

func (s *Stage) Execute(in any, c *gin.Context, lgr Logger) (any, *StageError)

Execute executes the stage by calling the F function followed by the E function if there's an error.

type StageError

type StageError struct {
	Code int // HTTP status code
	Obj  any // JSON response data
}

func Execute

func Execute(ch *Chain, c *gin.Context, lgr Logger) (any, *StageError)

Directories

Path Synopsis
examples
modules

Jump to

Keyboard shortcuts

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