scalar

package module
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Apr 9, 2022 License: MIT Imports: 21 Imported by: 0

README

Go-Scalar

PRs Welcome

Go-Scalar is a super-modular library to bootstrap your next golang web project. It can be used for strict API-only purposes as well as server-side rendering.

Features

Dependency Injection • Routing • Templating • Logging • Middleware • Caching • REST Router (beta)

Documentation

Read our GitHub Wiki, check out the Example Project or try run the code below

package main

import (
	. "github.com/infinytum/go-scalar"
	"github.com/infinytum/go-scalar/log"
)

var address = "0.0.0.0:8123"
var cacheKey = "greeting"

func main() {
	log.Info("Registering application routes...")

	DefaultRouter().GET("/hello", helloHandler)
	DefaultRouter().GET("/hello/:name", setHelloHandler)

	log.Infof("Server has started on %s", address)
	log.Error(DefaultRouter().ListenAndServe(address))
}

type HelloContext struct {
	Cache Cache `container:"type"`
}

func helloHandler(ctx HelloContext, res *Response, req *Request) {
	log.Infof("A friendly world is coming to say hello")

	var greeting string
	ctx.Cache.GetOrDefault(cacheKey, &greeting, "world")

	res.String("Hello " + greeting + "!")
}

func setHelloHandler(ctx HelloContext, res *Response, req *Request) {
	log.Infof("Setting a new greeting, I wonder what it is.")
	ctx.Cache.Set(cacheKey, req.Param("name"))
	res.String("A new greeting has been set :D")
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ResourcesDir is the base path of where all static resources like templates and assets are stored
	// This is dynamically set to the current working directory on startup
	ResourcesDir = ""

	// TemplatePrefix is a prefix that is appended to the ResourcesDir to get the base path for all templates
	// This is used by the default renderer implementation to figure out where to look for partials.
	TemplatePrefix = "/templates/"

	// AssetsPrefix is a prefix that is appended to the ResourcesDir to get the base path for all assets
	// This is used by the provided AssetsHandler implementation to serve files from
	AssetsPrefix = "/assets/"
)
View Source
var ErrorCacheMiss = errors.New("the given key was not found in the cache")

ErrorCacheMiss is returned when the cache could not find the given key

View Source
var ErrorNextHandlerInvalid = errors.New("middleware next parameter type is incorrect. Must be a func() error")

ErrorNextHandlerInvalid is returned when a middleware has an incorrect signature for the next() function

View Source
var (
	// ErrorTooManyArguments is returned when a handler has too many arguments
	ErrorTooManyArguments = errors.New("the specified handler has too many argument")
)

Functions

func AssetsDir

func AssetsDir() string

AssetsDir will return the absolute path of the configured assets directory

func AssetsHandler

func AssetsHandler(path string) func(res *Response, req *Request)

AssetsHandler will return a handler that can serve assets on a given path. AssetsHandler will look for the assets as ResourcesDir + AssetsPrefix on the file system. The path provided must be the same path as registered on the router.

func CacheKeyHash

func CacheKeyHash(key string) string

CacheKeyHash returns the SHA256 hash of a string for caching purposes

func HandleAssets

func HandleAssets(router Router) error

HandleAssets will register the AssetsHandler on a given router on the default path /assets

func HandleAssetsOnPath

func HandleAssetsOnPath(router Router, path string) error

HandleAssetsOnPath will register the AssetsHandler on a given router and a given path with the correct route param suffix

func Register

func Register(resolver interface{}, singleton bool) error

Register will register a new dependency as default for the return type of the function

func RegisterDB

func RegisterDB(name string, factory func() *bun.DB) error

RegisterDB registers a new database factory for a bun.DB connection

func RegisterNamed

func RegisterNamed(name string, resolver interface{}, singleton bool) error

RegisterNamed will register a new dependency under the given name

func RequestLogger

func RequestLogger(res *Response, req *Request, next func() error) (err error)

RequestLogger provides a simple middleware implementation that will log every request handled by scalar

func Resolve

func Resolve(obj interface{}) error

Resolve will resolve a dependency based on the target objects type

func ResolveNamed

func ResolveNamed(name string, obj interface{}) error

ResolveNamed will resolve a dependecy based on the given name

func TemplateDir

func TemplateDir() string

TemplateDir will return the absolute path of the configured templates directory

func ViewHandler

func ViewHandler(view string) func(res *Response, req *Request) error

ViewHandler will server a given template using the default rendering engine without any view bag contents

Types

type Cache

type Cache interface {
	// Contains returns whether a key is present in the cache
	Contains(key string) (bool, error)
	// Delete removes a cache entry by its key, will do nothing if the
	// key was not present in the cache
	Delete(key string) error
	// ExpireAfter will mark a cache key for expiration after a certain duration
	ExpireAfter(key string, duration time.Duration) error
	// Get will attempt to read a stored cache value into the given
	// out interface pointer or error if not present
	Get(key string, out interface{}) error
	// Get will attempt to read a stored cache value into the given
	// out interface pointer or return default if not found
	GetOrDefault(key string, out interface{}, def interface{}) error
	// Set will attempt to store a value in the cache with a given key
	Set(key string, val interface{}) error
}

Cache defines the minimum API surface for a valid scalar cache

func DefaultCache

func DefaultCache() (cache Cache)

DefaultCache will return the default cache instance for the scalar.Cache type

func NewMemoryCache

func NewMemoryCache() Cache

NewMemoryCache will create a new instance of the built-in go-scalar memory cache

type Handler

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

Handler defines a scalar handler

func NewHandler

func NewHandler(handler interface{}) (*Handler, error)

NewHandler will introspect the given handler and, if valid, return a new handler instance that can serve a route

func (*Handler) AddMiddleware

func (h *Handler) AddMiddleware(middleware interface{}) error

AddMiddleware adds a middleware into the chain

func (Handler) CanError

func (h Handler) CanError() bool

CanError returns true when the handler func is returning error

func (Handler) HandlerFunc

func (h Handler) HandlerFunc() HandlerFunc

HandlerFunc will generate the original handlers function without any chained middlewares

func (Handler) HasContext

func (h Handler) HasContext() bool

HasContext returns true if the position of a context argument has been detected

func (Handler) HasRequest

func (h Handler) HasRequest() bool

HasRequest returns true if the position of a scalar request argument has been detected

func (Handler) HasResponse

func (h Handler) HasResponse() bool

HasResponse returns true if the position of a scalar response argument has been detected

func (Handler) Serve

func (h Handler) Serve(req *Request, res *Response) error

Serve is the handler func that executes the handler and all the middlewares

type HandlerFunc

type HandlerFunc func(res *Response, req *Request) error

HandlerFunc describes the method signature of a scalar handler function that can process an incoming requests. A handler func masks all middleware and dependency injection behind a simple, easy to use interface

func HandlerChain

func HandlerChain(f HandlerFunc, middleware MiddlewareHandler) HandlerFunc

HandlerChain will chain a handler func and a middleware together to form a new, single handler func

type LogFields

type LogFields map[string]interface{}

LogFields is a type definition for cleaner code

func (LogFields) Clone

func (f LogFields) Clone() LogFields

Clone will clone a map of logfields into a new one

type Logger

type Logger interface {
	// Debug will write a debug log
	Debug(msg interface{})
	// Debugf will write a debug log sprintf-style
	Debugf(msg string, values ...interface{})
	// Error will write a error log
	Error(msg interface{})
	// Errorf will write a error log sprintf-style
	Errorf(msg string, values ...interface{})
	// Fatal will write a fatal log
	Fatal(msg interface{})
	// Fatalf will write a fatal log sprintf-style
	Fatalf(msg string, values ...interface{})
	// Field will add a field to a new logger and return it
	Field(name string, val interface{}) Logger
	// Fields will add multiple fields to a new logger and return it
	Fields(fields LogFields) Logger
	// Info will write a info log
	Info(msg interface{})
	// Infof will write a info log sprintf-style
	Infof(msg string, values ...interface{})
	// Trace will write a trace log
	Trace(msg interface{})
	// Tracef will write a trace log sprintf-style
	Tracef(msg string, values ...interface{})
	// Warn will write a warn log
	Warn(msg interface{})
	// Warnf will write a warn log sprintf-style
	Warnf(msg string, values ...interface{})
}

Logger defines the interface of a scalar compatible logger implementation

func DefaultLogger

func DefaultLogger() (logger Logger)

DefaultLogger will return the default logger instance for the scalar.Logger type

func NewBuiltinLogger

func NewBuiltinLogger() Logger

NewBuiltinLogger will create a new instance of the scalar builtin logger implementation

func NewZerologLogger

func NewZerologLogger() Logger

NewZerologLogger will create a new instance of the scalar zerolog implementation

type MiddlewareHandler

type MiddlewareHandler func(res *Response, req *Request, next func() error) error

MiddlewareHandler is a special kind of HandlerFunc, that receives the next handler in line as its third parameter.

type Renderer

type Renderer interface {
	// Render will load a template file and render the template
	// within using the viewbag as a context
	Render(view string, bag ViewBag) (string, error)
}

Renderer defines the interface of a scalar compatible renderer

func DefaultRenderer

func DefaultRenderer() (renderer Renderer)

DefaultRenderer will return the default renderer instance for the scalar.Renderer type

func NewHandlebarsRenderer

func NewHandlebarsRenderer() Renderer

NewHandlebarsRenderer will return a new instance of the scalar handlebars renderer implementation

type Request

type Request struct {
	*http.Request
	Params map[string]string
	// contains filtered or unexported fields
}

Request is the scalar implementation of a request which wraps around a regular http.Request object.

func NewRequest

func NewRequest(req *http.Request) *Request

NewRequest will create a new instance of a scalar request for the given http.Request object

func (Request) HasContentType added in v1.1.1

func (r Request) HasContentType(mimetype string) bool

HasContentType determines whether a request has a given mime type as its content type

func (Request) Metadata

func (r Request) Metadata(key string) string

Metadata returns metadata for this request, if there is any

func (Request) Param

func (r Request) Param(name string) string

Param returns the route parameter or empty string if not found

func (Request) ParamOrDefault

func (r Request) ParamOrDefault(name string, def string) string

ParamOrDefault returns the route parameter or a custom default if not found

func (Request) SetMetadata

func (r Request) SetMetadata(key string, value string)

SetMetadata will set the metadata value for a given key

type Response

type Response struct {
	http.ResponseWriter
	ViewBag ViewBag
}

Response is the scalar implementation of a response which wraps around a regular http.ResponseWriter object

func NewResponse

func NewResponse(res http.ResponseWriter) *Response

NewResponse will create a new instance of a scalar response for the given http.ResponseWriter object

func (Response) JSON

func (r Response) JSON(body interface{}) error

JSON writes any object to the response body as JSON

func (Response) PrettyJSON

func (r Response) PrettyJSON(body interface{}) error

PrettyJSON writes any object to the response body as pretty JSON

func (Response) String

func (r Response) String(body string) error

String will write a string to the response body

func (Response) View

func (r Response) View(view string) error

View will use the default renderer to load a view and render it to the response body using the response object's ViewBag

type RouteGroup

type RouteGroup struct {
	Delete      map[string]*Handler
	Get         map[string]*Handler
	Head        map[string]*Handler
	Post        map[string]*Handler
	Put         map[string]*Handler
	Middlewares []interface{}
}

RouteGroup is the default implementation of a generic Routeable

func NewRouteGroup added in v1.1.1

func NewRouteGroup() *RouteGroup

NewRouteGroup will create a new, empty instance of the default Routeable implementation

func (*RouteGroup) DELETE added in v1.1.1

func (r *RouteGroup) DELETE(path string, handler interface{}) error

DELETE will register a new route using the DELETE method

func (*RouteGroup) GET added in v1.1.1

func (r *RouteGroup) GET(path string, handler interface{}) error

GET will register a new route using the GET method

func (*RouteGroup) HEAD added in v1.1.1

func (r *RouteGroup) HEAD(path string, handler interface{}) error

HEAD will register a new route using the HEAD method

func (*RouteGroup) POST added in v1.1.1

func (r *RouteGroup) POST(path string, handler interface{}) error

POST will register a new route using the POST method

func (*RouteGroup) PUT added in v1.1.1

func (r *RouteGroup) PUT(path string, handler interface{}) error

PUT will register a new route using the PUT method

func (*RouteGroup) WithMiddleware added in v1.1.1

func (r *RouteGroup) WithMiddleware(middleware interface{}) error

WithMiddleware will add a middleware to all registered and future routes in this route group

type Routeable

type Routeable interface {
	DELETE(path string, handler interface{}) error
	GET(path string, handler interface{}) error
	HEAD(path string, handler interface{}) error
	POST(path string, handler interface{}) error
	PUT(path string, handler interface{}) error
	WithMiddleware(handler interface{}) error
}

Routeable defines the functions necessary on any object that can register routes and middlewares

type Router

type Router interface {
	Routeable
	Group(path string, callback func(router Routeable))
	ListenAndServe(address string) error
}

Router defines a superset of a Routeable that can create route groups as well as start a webserver

func DefaultRouter

func DefaultRouter() (router Router)

DefaultRouter will return the default router instance for the scalar.Router type

func NewBunRouter

func NewBunRouter() Router

NewBunRouter will create new instance of the scalar bun router implementation

type ViewBag

type ViewBag map[string]interface{}

ViewBag is a type definition to keep code readable

func (ViewBag) Delete

func (v ViewBag) Delete(key string)

Delete will remove an entry from the ViewBag

func (ViewBag) Set

func (v ViewBag) Set(key string, val interface{})

Set will set a new value for the given key in the ViewBag

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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