webutil

package
v8.7.1 Latest Latest
Warning

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

Go to latest
Published: Feb 7, 2025 License: MIT Imports: 37 Imported by: 0

Documentation

Overview

Package webutil provides functions for making developing a website easier.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AdminAPIListenAndServe deprecated

func AdminAPIListenAndServe(ctx context.Context, healthy ...func() error)

Deprecated: Use AdminAPIListenAndServeWithAddress instead

func AdminAPIListenAndServeWithAddress added in v8.7.0

func AdminAPIListenAndServeWithAddress(ctx context.Context, host, port string)

func AssetDefaultDev added in v8.4.0

func AssetDefaultDev() (AssetPathPrefix, AssetCacheDuration)

AssetDefaultDev provides the suggested defaults for development environments.

func AssetDefaultProd added in v8.4.0

func AssetDefaultProd() (AssetPathPrefix, AssetCacheDuration)

AssetDefaultProd provides the suggested defaults for production environments.

func AuthTemplateFunctions

func AuthTemplateFunctions(r *http.Request) template.FuncMap

AuthTemplateFunctions returns auth related template functions. These can then directly be used in the templates without having to add the auth info manually to the template data.

Function `func AuthIsAuthenticated() bool` returns true, if the user is logged in.

Function `func AuthInfo() *AuthInfo` returns the AuthInfo, if the user is logged and `nil` otherwise.

Example:

{{ if AuthIsAuthenticated }}
  <span class="navbar-text">Hello, <em>{{ AuthInfo.Name }}</em>!</span>
{{ else }}
  <a class="nav-link" href="/auth/login">Login</span></a>
{{ end }}

func DevAuthMiddleware

func DevAuthMiddleware(roles ...string) func(http.Handler) http.Handler

DevAuthMiddleware is a dummy auth middleware that does not any actual authentication. It is supposed to be used for local development. The roles parameter defines which roles can be selected in the dummy login form.

func ListenAndServeWithContext

func ListenAndServeWithContext(ctx context.Context, addr string, handler http.Handler) error

ListenAndServeWithContext does the same as http.ListenAndServe with the difference that is properly utilises the context. This means it does a graceful shutdown when the context is done and a context cancellation gets propagated down to the actual request context.

func NewAuthMiddleware

func NewAuthMiddleware(ctx context.Context, config AuthConfig) (func(http.Handler) http.Handler, error)

func ProvideHandler added in v8.4.0

func ProvideHandler(c *dig.Container, fn any) error

Helper to provide a handler to dependency injection.

func SessionFromContext

func SessionFromContext(ctx context.Context) (*sessions.Session, error)

SessionFromContext extracts the Session store from the given context. The session store is injected into the request via the SessionMiddleware. Therefore it is required to use this middleware to be able to get the store.

func SessionFromRequest

func SessionFromRequest(r *http.Request) (*sessions.Session, error)

SessionFromRequest returns the results of SessionFromContext for the context of the given request.

func SessionMiddleware

func SessionMiddleware(secret SessionSecret, opts ...SessionMiddlewareOption) func(http.Handler) http.Handler

SessionMiddleware inizializes the session store and injects it into the context of the requests.

func SessionSecretSourceRedis

func SessionSecretSourceRedis(ctx context.Context, client RedisSessioner, prefix string) ([]byte, error)

SessionSecretSourceRedis stores the session secrets in Redis. If the key does not exist yet, it will create a new one.

func SessionSecretSourceVolatile

func SessionSecretSourceVolatile() []byte

SessionSecretSourceVolatile creates a session secret that is stored in memory only. This implies, that all session data is lost after an application restart and an application cannot have more than one replicas.

func ViewError added in v8.3.0

func ViewError(status int, err error) http.HandlerFunc

func ViewErrorf added in v8.3.0

func ViewErrorf(status int, text string, a ...interface{}) http.HandlerFunc

func ViewInlineHTML added in v8.3.0

func ViewInlineHTML(status int, data string, a ...any) http.HandlerFunc

func ViewJSON added in v8.3.0

func ViewJSON(status int, data any) http.HandlerFunc

func ViewNoContent added in v8.6.0

func ViewNoContent(status int) http.HandlerFunc

func ViewRedirect added in v8.3.0

func ViewRedirect(status int, location string, args ...interface{}) http.HandlerFunc

func WrapView added in v8.3.0

func WrapView(fn func(*http.Request) Response) http.HandlerFunc

Types

type AssetCacheDuration added in v8.4.0

type AssetCacheDuration time.Duration

AssetCacheDuration defines the duration for the caching headers of assets. It is suggested to use a long time (e.g. a year) for production and a second for development.

type AssetFS added in v8.4.0

type AssetFS fs.FS

AssetFS is the fs.FS that is used to server assets. It is a separate type to support dependency injection.

type AssetPathPrefix added in v8.4.0

type AssetPathPrefix string

AssetPathPrefix is the prefix that is prepended to each asset path. It is suggested to use the commit hash in production and "dev" for development. This way the server always serves new assets on rollout, even if they are still cached.

type AuthConfig

type AuthConfig struct {
	Secrets     AuthSecrets
	ConfigURL   string
	BaseURL     string
	SigningAlgs []string
}

func (*AuthConfig) Bind

func (c *AuthConfig) Bind(cmd *cobra.Command)

type AuthInfo

type AuthInfo struct {
	Username    string `json:"preferred_username"`
	Name        string `json:"name"`
	RealmAccess struct {
		Roles []string `json:"roles"`
	} `json:"realm_access"`
}

func AuthInfoFromContext

func AuthInfoFromContext(ctx context.Context) *AuthInfo

AuthInfoFromContext extracts the AuthInfo from the given context. The AuthInfo is injected into the request via the AuthMiddleware. Therefore it is required to use this middleware to be able to get the AuthInfo.

func AuthInfoFromRequest

func AuthInfoFromRequest(r *http.Request) *AuthInfo

AuthInfoFromRequest extracts the AuthInfo from the context within the given request. The AuthInfo is injected into the request via the AuthMiddleware. Therefore it is required to use this middleware to be able to get the AuthInfo.

func (AuthInfo) HasRole

func (i AuthInfo) HasRole(want string) bool

HasRole returns true, if the user has the given role. The role name needs to be allowlisted in the AuthMiddleware, otherwise it will return false even if the user is in the team.

type AuthSecrets

type AuthSecrets struct {
	ClientID     string `vault:"client_id"`
	ClientSecret string `vault:"client_secret"`
	SessionKey   string `vault:"session_key"`
}

type GoTemplateViewer added in v8.3.0

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

func NewGoTemplateViewer added in v8.3.0

func NewGoTemplateViewer(fs fs.FS, fms ...TemplateFuncMap) *GoTemplateViewer

func (*GoTemplateViewer) HTML added in v8.3.0

func (v *GoTemplateViewer) HTML(status int, filename string, data any) http.HandlerFunc

func (*GoTemplateViewer) Render added in v8.3.0

func (v *GoTemplateViewer) Render(filename string, r *http.Request, data any) (*bytes.Buffer, error)

type Handler added in v8.4.0

type Handler interface {
	Register(chi.Router)
}

Handler is the interface that HTTP handlers need to implement to get picked up and served by the Server.

type Middlewares added in v8.5.0

type Middlewares []func(http.Handler) http.Handler

Middlewares defines all chi middlewares. It needs to be provided as list to dig and not as single middlewares, since order matters and dig does not guarantee any ordering. To just append middlewares, you need to append them to the ones from `DefaultMiddlewares`

func DefaultMiddlewares added in v8.5.0

func DefaultMiddlewares() Middlewares

type RedisSessioner

type RedisSessioner interface {
	Get(context.Context, string) *redis.StringCmd
	Set(context.Context, string, interface{}, time.Duration) *redis.StatusCmd
}

type Response

type Response = http.HandlerFunc

type ResponseHandlerFunc

type ResponseHandlerFunc func(*View, *http.Request) Response

type Server added in v8.4.0

type Server struct {
	AssetFS            AssetFS
	AssetPathPrefix    AssetPathPrefix
	AssetCacheDuration AssetCacheDuration
	Handlers           []Handler
	Middlewares        Middlewares
}

Server is a web server targeted on projects that have a user-facing web interface. It supports dependency injection using dig.

func NewServer added in v8.4.0

func NewServer(p ServerParams) *Server

func (*Server) Run added in v8.4.0

func (s *Server) Run(ctx context.Context) error

func (*Server) Workers added in v8.4.0

func (s *Server) Workers() []runutil.Worker

Workers defines the workers, making it compatible with runutil.

type ServerParams added in v8.4.0

type ServerParams struct {
	dig.In

	AssetFS            AssetFS
	AssetPathPrefix    AssetPathPrefix
	AssetCacheDuration AssetCacheDuration
	Handlers           []Handler   `group:"handler"`
	Middlewares        Middlewares `optional:"true"`
}

ServerParams defines all parameters that are needed for the Server. Its fields can be injected using dig.

type SessionMiddlewareOption

type SessionMiddlewareOption func(c *sessionMiddlewareConfig)

func SessionMiddlewareCookieDomain

func SessionMiddlewareCookieDomain(domain string) SessionMiddlewareOption

func SessionMiddlewareCookieUnsecure

func SessionMiddlewareCookieUnsecure() SessionMiddlewareOption

type SessionSecret

type SessionSecret []byte

type TemplateFuncMap

type TemplateFuncMap func(*http.Request) template.FuncMap

func SimpleTemplateFuncMap

func SimpleTemplateFuncMap(name string, fn interface{}) TemplateFuncMap

func SimpleTemplateFuncMaps

func SimpleTemplateFuncMaps(fm template.FuncMap) TemplateFuncMap

type View deprecated

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

Deprecated: M0003 Use GoTemplateViewer and View* functions instead.

func (*View) Error deprecated

func (v *View) Error(status int, err error) http.HandlerFunc

Deprecated: M0003 Use GoTemplateViewer and View* functions instead.

func (*View) Errorf deprecated

func (v *View) Errorf(status int, text string, a ...interface{}) http.HandlerFunc

Deprecated: M0003 Use GoTemplateViewer and View* functions instead.

func (*View) HTML deprecated

func (v *View) HTML(status int, filename string, data any) http.HandlerFunc

Deprecated: M0003 Use GoTemplateViewer and View* functions instead.

func (*View) JSON deprecated

func (v *View) JSON(status int, data any) http.HandlerFunc

Deprecated: M0003 Use GoTemplateViewer and View* functions instead.

func (*View) Redirect deprecated

func (v *View) Redirect(status int, location string, args ...interface{}) http.HandlerFunc

Deprecated: M0003 Use GoTemplateViewer and View* functions instead.

type ViewHandler deprecated

type ViewHandler struct {
	FS       fs.FS
	FuncMaps []TemplateFuncMap
}

Deprecated: M0003 Use GoTemplateViewer and View* functions instead.

func NewViewHandler deprecated

func NewViewHandler(fs fs.FS, fms ...TemplateFuncMap) *ViewHandler

Deprecated: M0003 Use GoTemplateViewer and View* functions instead.

func (*ViewHandler) Render deprecated

func (h *ViewHandler) Render(filename string, r *http.Request, d interface{}) (*bytes.Buffer, error)

Deprecated: M0003 Use GoTemplateViewer and View* functions instead.

func (*ViewHandler) Wrap deprecated

Deprecated: M0003 Use GoTemplateViewer and View* functions instead.

Jump to

Keyboard shortcuts

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