server

package
v0.0.0-...-60192f8 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2024 License: AGPL-3.0 Imports: 43 Imported by: 0

Documentation

Overview

Package server is the main Readeck HTTP server. It defines common middlewares, guards, permission handlers, etc.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetCSPHeader

func GetCSPHeader(r *http.Request) csp.Policy

GetCSPHeader extracts the current CSPHeader from the request's context.

func GetTemplate

func GetTemplate(name string) (*jet.Template, error)

GetTemplate returns a template from the current views.

func Logger

func Logger() func(next http.Handler) http.Handler

Logger is a middleware that logs requests.

Types

type Error

type Error struct {
	Location string `json:"location"`
	Error    string `json:"error"`
}

Error is mainly used to return payload/querystring errors.

type Etager

type Etager interface {
	GetSumStrings() []string
}

Etager must provides a function that returns a list of strings used to build an etag header.

type LastModer

type LastModer interface {
	GetLastModified() []time.Time
}

LastModer must provides a function that returns a list of times used to build a Last-Modified header.

type Link struct {
	URL  string
	Rel  string
	Type string
}

Link contains a "Link" header information.

func NewLink(url string) Link

NewLink returns a new Link instance.

func (Link) WithRel

func (l Link) WithRel(rel string) Link

WithRel adds a "rel" value to the link.

func (Link) WithType

func (l Link) WithType(t string) Link

WithType adds a "type" value to the link.

func (Link) Write

func (l Link) Write(w http.ResponseWriter)

Write adds the header to a ResponseWriter.

type Message

type Message struct {
	Status  int     `json:"status"`
	Message string  `json:"message"`
	Errors  []Error `json:"errors,omitempty"`
}

Message is used by the server's Message() method.

type PageLink struct {
	Index int
	URL   string
}

PageLink contains a link to a page in a Pagination instance.

type Pagination

type Pagination struct {
	URL          *url.URL
	Limit        int
	Offset       int
	TotalCount   int
	TotalPages   int
	CurrentPage  int
	First        int
	Last         int
	Next         int
	Previous     int
	FirstPage    string
	LastPage     string
	NextPage     string
	PreviousPage string
	PageLinks    []PageLink
}

Pagination holds all the information regarding pagination.

func (p Pagination) GetLink(offset int) string

GetLink returns a new url string with limit and offset values.

func (p Pagination) GetPageLinks() []PageLink

GetPageLinks returns the links that can be used in a template.

type PaginationForm

type PaginationForm struct {
	*forms.Form
}

PaginationForm is a default form for pagination.

func (*PaginationForm) Limit

func (f *PaginationForm) Limit() int

Limit returns the current limit or zero if none was given.

func (*PaginationForm) Offset

func (f *PaginationForm) Offset() int

Offset returns the current offset or 0 if none was given.

func (*PaginationForm) SetLimit

func (f *PaginationForm) SetLimit(v int)

SetLimit sets the limit's value. It's used to set a default limit before binding the form.

type Server

type Server struct {
	Router   *chi.Mux
	BasePath string
}

Server is a wrapper around chi router.

func New

func New(basePath string) *Server

New create a new server. Routes must be added manually before calling ListenAndServe.

func (*Server) AbsoluteURL

func (s *Server) AbsoluteURL(r *http.Request, parts ...string) *url.URL

AbsoluteURL resolve the absolute URL for the given ref path parts. If the ref starts with "./", it will resolve relative to the current URL.

func (*Server) AddFlash

func (s *Server) AddFlash(w http.ResponseWriter, r *http.Request, typ, msg string) error

AddFlash saves a flash message in the session.

func (*Server) AddRoute

func (s *Server) AddRoute(pattern string, handler http.Handler)

AddRoute adds a new route to the server, prefixed with the BasePath.

func (*Server) AssetURL

func (s *Server) AssetURL(r *http.Request, name string) string

AssetURL returns the real URL for a given asset.

func (*Server) AuthenticatedRouter

func (s *Server) AuthenticatedRouter(middlewares ...func(http.Handler) http.Handler) chi.Router

AuthenticatedRouter returns a chi.Router instance with middlewares to force authentication.

func (*Server) CannonicalPaths

func (s *Server) CannonicalPaths(next http.Handler) http.Handler

CannonicalPaths cleans the URL path and removes trailing slashes. It returns a 308 redirection so any form will pass through.

func (*Server) CompressResponse

func (s *Server) CompressResponse(next http.Handler) http.Handler

CompressResponse returns a gzipped response for some content types. It uses gzhttp that provides a BREACH mittigation.

func (*Server) Csrf

func (s *Server) Csrf(next http.Handler) http.Handler

Csrf setup the CSRF protection.

func (*Server) CurrentPath

func (s *Server) CurrentPath(r *http.Request) string

CurrentPath returns the path of the current request after striping the server's base path. This value can later be used in the AbsoluteURL or Redirect functions.

func (*Server) Error

func (s *Server) Error(w http.ResponseWriter, r *http.Request, err error)

Error sends an HTTP 500 and log the given error.

func (*Server) ErrorPages

func (s *Server) ErrorPages(next http.Handler) http.Handler

ErrorPages is a middleware that overrides the response writer so that, under some conditions, it can send a response matching the "accept" request header.

Conditions are: response status must be >= 400, its content-type is text/plain and it has some content.

func (*Server) Flashes

func (s *Server) Flashes(r *http.Request) []sessions.FlashMessage

Flashes returns the flash messages retrieved from the session in the session middleware.

func (*Server) GetPageParams

func (s *Server) GetPageParams(r *http.Request, defaultLimit int) *PaginationForm

GetPageParams returns the pagination parameters from the query string.

func (s *Server) GetPaginationLinks(r *http.Request, p Pagination) []Link

GetPaginationLinks returns a list of Link instances suitable for pagination.

func (*Server) GetReqID

func (s *Server) GetReqID(r *http.Request) string

GetReqID returns the request ID.

func (*Server) GetSession

func (s *Server) GetSession(r *http.Request) *sessions.Session

GetSession returns the session currently stored in context. It will panic (on purpose) if the route is not using the WithSession() middleware.

func (*Server) Init

func (s *Server) Init()

Init initializes the server and the template engine.

func (*Server) InitRequest

func (s *Server) InitRequest(next http.Handler) http.Handler

InitRequest update the scheme and host on the incoming HTTP request URL (r.URL), based on provided headers and/or current environnement.

It also checks the validity of the host header when the server is not running in dev mode.

func (*Server) InitSession

func (s *Server) InitSession() error

InitSession creates the session handler.

func (*Server) IsTurboRequest

func (s *Server) IsTurboRequest(r *http.Request) bool

IsTurboRequest returns true when the request was made with an x-turbo header.

func (*Server) LoadLocale

func (s *Server) LoadLocale(next http.Handler) http.Handler

LoadLocale is a middleware that loads the correct locale for the current user. It defaults to English if no user is connected or no language is set.

func (*Server) Locale

func (s *Server) Locale(r *http.Request) *locales.Locale

Locale returns the current user's locale.

func (*Server) Log

func (s *Server) Log(r *http.Request) *log.Entry

Log returns a log entry including the request ID.

func (*Server) Message

func (s *Server) Message(w http.ResponseWriter, r *http.Request, message *Message)

Message sends a JSON formatted message response.

func (*Server) NewPagination

func (s *Server) NewPagination(r *http.Request, count, limit, offset int) Pagination

NewPagination creates a new Pagination instance base on the current request.

func (*Server) Redirect

func (s *Server) Redirect(w http.ResponseWriter, r *http.Request, ref ...string)

Redirect yields a 303 redirection with a location header. The given "ref" values are joined togegher with the server's base path to provide a full absolute URL.

func (*Server) Render

func (s *Server) Render(w http.ResponseWriter, r *http.Request, status int, value interface{})

Render converts any value to JSON and sends the response.

func (*Server) RenderTemplate

func (s *Server) RenderTemplate(w http.ResponseWriter, r *http.Request,
	status int, name string, ctx TC,
)

RenderTemplate yields an HTML response using the given template and context.

func (*Server) RenderTurboStream

func (s *Server) RenderTurboStream(
	w http.ResponseWriter, r *http.Request,
	name, action, target string, ctx interface{},
)

RenderTurboStream yields an HTML response with turbo-stream content-type using the given template and context. The template result is enclosed in a turbo-stream tag with action and target as specified. You can call this method as many times as needed to output several turbo-stream tags in the same HTTP response.

func (*Server) SendPaginationHeaders

func (s *Server) SendPaginationHeaders(
	w http.ResponseWriter, r *http.Request,
	p Pagination,
)

SendPaginationHeaders compute and set the pagination headers.

func (*Server) SetSecurityHeaders

func (s *Server) SetSecurityHeaders(next http.Handler) http.Handler

SetSecurityHeaders adds some headers to improve client side security.

func (*Server) Status

func (s *Server) Status(w http.ResponseWriter, _ *http.Request, status int)

Status sends a text plain response with the given status code.

func (*Server) TemplateVars

func (s *Server) TemplateVars(r *http.Request) jet.VarMap

TemplateVars returns the default variables set for a template in the request's context.

func (*Server) TextMessage

func (s *Server) TextMessage(w http.ResponseWriter, r *http.Request, status int, msg string)

TextMessage sends a JSON formatted message response with a status and a message.

func (*Server) WithCacheControl

func (s *Server) WithCacheControl(next http.Handler) http.Handler

WithCacheControl sends the global caching headers.

func (*Server) WithCaching

func (s *Server) WithCaching(next http.Handler) http.Handler

WithCaching is a middleware that checks if an Etag and/or a Last-Modified headers are sent with the response. If the request has the correspondign cache header and theys match the request stops with a 304.

func (*Server) WithPermission

func (s *Server) WithPermission(obj, act string) func(next http.Handler) http.Handler

WithPermission enforce a permission check on the request's path for the given action.

In the RBAC configuration, the user's group is the subject, the given "obj" is the object and "act" is the action.

func (*Server) WithRedirectLogin

func (s *Server) WithRedirectLogin(next http.Handler) http.Handler

WithRedirectLogin sets the unauthorized handler to redirect to the login page.

func (*Server) WithSession

func (s *Server) WithSession() func(next http.Handler) http.Handler

WithSession initialize a session handler that will be available on the included routes.

func (*Server) WriteEtag

func (s *Server) WriteEtag(w http.ResponseWriter, r *http.Request, taggers ...Etager)

WriteEtag adds an Etag header to the response, based on the values sent by GetSumStrings. The build date is always included.

func (*Server) WriteLastModified

func (s *Server) WriteLastModified(w http.ResponseWriter, r *http.Request, moders ...LastModer)

WriteLastModified adds a Last-Modified headers using the most recent date of GetLastModified and the build date.

type TC

type TC map[string]interface{}

TC is a simple type to carry template context.

func (TC) SetBreadcrumbs

func (tc TC) SetBreadcrumbs(items [][2]string)

SetBreadcrumbs sets the current page's breadcrumbs.

Jump to

Keyboard shortcuts

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