server

package
v0.0.0-...-d1a9080 Latest Latest
Warning

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

Go to latest
Published: May 5, 2021 License: AGPL-3.0 Imports: 38 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

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 FlashMessage

type FlashMessage struct {
	Type    string
	Message string
}

FlashMessage contains a message type and content.

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 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 {
	Limit  int `json:"limit"`
	Offset int `json:"offset"`
}

PaginationForm is a default form for pagination

func (*PaginationForm) Validate

func (pf *PaginationForm) Validate(f *form.Form)

Validate validates the PaginationForm values

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() chi.Router

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

func (*Server) BindQueryString

func (s *Server) BindQueryString(r *http.Request, dst interface{}) *Message

BindQueryString binds the request's query string with the given pointer to a struct of data. If the destination implements Validate(), it runs the validation as well.

func (*Server) Csrf

func (s *Server) Csrf() func(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) []FlashMessage

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

func (*Server) GetPageParams

func (s *Server) GetPageParams(r *http.Request) (*PaginationForm, *form.Form)

GetPageParams returns the pagination parameters from the query string

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) 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 store.

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

func (s *Server) ListenAndServe() error

ListenAndServe starts the HTTP server

func (*Server) LoadJSON

func (s *Server) LoadJSON(r *http.Request, dst interface{}) *Message

LoadJSON loads the JSON payload from the request body to the destination variable. If the destination implements Validate(), it runs the validation as well.

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,
	count, limit, offset int,
)

SendPaginationHeaders compute and set the pagination headers

func (*Server) SetSecurityHeaders

func (s *Server) SetSecurityHeaders() func(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) 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) Validate

func (s *Server) Validate(data interface{}) *Message

Validate runs the validation on a given destination data and returns a formatted message with the encountered errors, if any.

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(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 request's path is the object and "act" is the action.

func (*Server) WithSession

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

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

func (*Server) WriteEtag

func (s *Server) WriteEtag(w http.ResponseWriter, i 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, i 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.

Jump to

Keyboard shortcuts

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