scalar

package module
v1.1.0 Latest Latest
Warning

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

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

README

Go-Scalar

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.

Example Project

An example project is provided right here: https://github.com/Infinytum/go-scalar-example

Documentation

Please refer to this projects GitHub Wiki for documentation: https://github.com/Infinytum/go-scalar/wiki

Example

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   = ""
	TemplatePrefix = "/templates/"
	AssetsPrefix   = "/assets/"
)
View Source
var ErrorCacheMiss = errors.New("the given key was not found in the cache")
View Source
var ErrorNextHandlerInvalid = errors.New("middleware next parameter type is incorrect. Must be a func() error")
View Source
var (
	// Errors that can be used by developers down the line to catch specific states in their app
	ErrorTooManyArguments = errors.New("the specified handler has too many argument")
)

Functions

func AssetsDir

func AssetsDir() string

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 NewBuiltinLogger

func NewBuiltinLogger() *builtinLogger

func NewBunRouter

func NewBunRouter() *bunRouter

func NewHandlebarsRenderer

func NewHandlebarsRenderer() *handlebarsRenderer

func NewMemoryCache

func NewMemoryCache() *memoryCache

func NewZerologLogger

func NewZerologLogger() *zerologLogger

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

Register will register a new dependency under the given name

func RequestLogger

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

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

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

type Handler

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

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{}

func (LogFields) Clone

func (f LogFields) Clone() LogFields

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{})
}

func DefaultLogger

func DefaultLogger() (logger Logger)

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

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)
}

func DefaultRenderer

func DefaultRenderer() (renderer Renderer)

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

type Request

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

func NewRequest

func NewRequest(req *http.Request) *Request

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 emtpy 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)

type Response

type Response struct {
	http.ResponseWriter
	ViewBag ViewBag
}

func NewResponse

func NewResponse(res http.ResponseWriter) *Response

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 respones object's ViewBag

type RouteGroup

type RouteGroup interface {
	Routeable
}

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
}

type Router

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

func DefaultRouter

func DefaultRouter() (router Router)

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

type ScalarRouteGroup

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

func NewScalarRouteGroup

func NewScalarRouteGroup() *ScalarRouteGroup

func (*ScalarRouteGroup) DELETE

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

func (*ScalarRouteGroup) GET

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

func (*ScalarRouteGroup) HEAD

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

func (*ScalarRouteGroup) POST

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

func (*ScalarRouteGroup) PUT

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

func (*ScalarRouteGroup) WithMiddleware

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

type ViewBag

type ViewBag map[string]interface{}

func (ViewBag) Delete

func (v ViewBag) Delete(key string)

func (ViewBag) Set

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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