webutil

package
v3.12.0 Latest Latest
Warning

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

Go to latest
Published: Mar 15, 2022 License: MIT Imports: 32 Imported by: 1

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 added in v3.5.1

func AdminAPIListenAndServe(ctx context.Context, group *errgroup.Group, fnDone func())

func AuthTemplateFunctions

func AuthTemplateFunctions(r *http.Request, t *template.Template) *template.Template

AuthTemplateFunctions curries the given Template with auth related 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 HandleHealth

func HandleHealth(w http.ResponseWriter, r *http.Request, _ httprouter.Params)

HandleHealth returns a simple HTTP handler, that responds with 200 OK as long as the context is not done. When the context is done, it returns with 503. This only works, if the BaseContext of the http server gets canceled on shutdown. See ListenAndServerWithContext for details. Deprecated: Use AdminAPIListenAndServe instead.

func ListenAndServerWithContext

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

ListenAndServerWithContext 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 RespondError

func RespondError(w http.ResponseWriter, err error) bool

RespondError sends an error ID to the client and logs the error, if it is not nil. It returns true, if the error was not nil. This makes it possible to do condensed error checking:

err := DoSomething()
if webutil.RespondError(w, err) {
    return
}

func RespondJSON

func RespondJSON(w http.ResponseWriter, data interface{})

RespondJSON sets the proper content type and sends the given data as JSON to the client.

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 SessionSecretSourceRedis added in v3.3.0

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 TemplateFuncPrettyTime added in v3.3.0

func TemplateFuncPrettyTime(value interface{}) (string, error)

Types

type AuthInfo

type AuthInfo struct {
	GitHubToken string
	UpdatedAt   time.Time

	Login string
	Name  string
	Teams []string
}

AuthInfo contains data about the currently logged in user.

func AuthInfoFromContext

func AuthInfoFromContext(ctx context.Context) (*AuthInfo, error)

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, error)

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

func (i AuthInfo) InTeam(want string) bool

InTeam returns true, if the user is in the given team. The team name needs to be whitelisted in the AuthMiddleware, otherwise it will return false even if the user is in the team.

type Middleware

type Middleware func(next http.Handler) http.Handler

Middleware is a function that wraps an http.Handler. The function is supposed to call the next handler to continue to execute the process. This type is used by the MiddlewareChain to allow an easy usage of multiple middlewares which makes it easy to see the proper calling order.

func AuthMiddleware

func AuthMiddleware(teams ...string) Middleware

AuthMiddleware is an HTTP request middleware that adds login endpoints. The request makes use of sessions, therefore the SessionMiddleware is required.

The teams argument contains a whitelist of team names, that are copied into the AuthInfo, if the user is in those teams. It is desirable to copy only the needed subset of teams into the AuthInfo, because this data is carried in the session cookie.

Endpoint "/auth/login" initiates the user login and redirects them to the GitHub OAuth page.

Endpoint "/auth/callback" gets called by the user after being redirected from GitHub after a successful login.

func SessionMiddleware

func SessionMiddleware(secret SessionSecret, opts ...SessionMiddlewareOption) Middleware

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

type MiddlewareChain

type MiddlewareChain []Middleware

MiddlewareChain is a builder for an http.Handler out of multiple middlewares.

func NewMiddlewareChain

func NewMiddlewareChain() MiddlewareChain

NewMiddlewareChain initializes an empty MiddlewareChain.

func (MiddlewareChain) Finally

func (c MiddlewareChain) Finally(h http.Handler) http.Handler

Finally builds the http.Handler that is used by the HTTP server.

func (MiddlewareChain) Then

Then defines the next middleware to call.

type RedisSessioner added in v3.3.0

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

type SessionMiddlewareOption

type SessionMiddlewareOption func(c *sessionMiddlewareConfig)

func SessionMiddlewareCookieDomain

func SessionMiddlewareCookieDomain(domain string) SessionMiddlewareOption

func SessionMiddlewareCookieUnsecure added in v3.1.0

func SessionMiddlewareCookieUnsecure() SessionMiddlewareOption

type SessionSecret

type SessionSecret []byte

type TemplateRenderer added in v3.3.0

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

func NewTemplateRenderer added in v3.3.0

func NewTemplateRenderer(box *embed.FS, opts ...TemplateRendererOption) *TemplateRenderer

func (*TemplateRenderer) RespondHTML added in v3.3.0

func (tr *TemplateRenderer) RespondHTML(writer http.ResponseWriter, request *http.Request, name string, data interface{})

type TemplateRendererOption added in v3.3.0

type TemplateRendererOption func(*http.Request, *template.Template) *template.Template

func TemplateRendererFunc added in v3.3.0

func TemplateRendererFunc(name string, fn interface{}) TemplateRendererOption

Jump to

Keyboard shortcuts

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