server

package
v0.1.7 Latest Latest
Warning

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

Go to latest
Published: Jul 30, 2021 License: AGPL-3.0 Imports: 22 Imported by: 0

Documentation

Overview

Package server provides classes and functions for the HTTP server side of the middleware.

In particular, the package handles client sessions by producing credentials for logged user and by verifying these credentials for each request.

It is a wrapper around net/http.

Index

Constants

View Source
const (
	InternalHttpErrorMsg     = "Internal error"
	UnauthorizedHttpErrorMsg = "Unauthorized"
)
View Source
const (
	// Name of the cookie for sessions.
	SessionName = "s"

	// Name of the cookie for unlogged users.
	SessionUnlogged = "u"
)

Variables

View Source
var Ok bool

Ok indicates whether the package is usable. May be false if there is no configuration for the package.

View Source
var SessionOptions gs.Options

SessionOptions reflects the configured options for sessions. Modifying it has no effect on the sessions generated by the package.

Functions

func AddSessionIdToRequest

func AddSessionIdToRequest(req *http.Request, sessionId string)

AddSessionIdToRequest adds a session id to an http.Request. This function is meant to be used by HTTP clients and tests.

func BaseURL

func BaseURL() string

BaseURL returns the URL of the application.

func Compress

func Compress(h http.Handler) http.Handler

Compress gzip compresses HTTP responses for clients that support it via the 'Accept-Encoding' header.

Compressing TLS traffic may leak the page contents to an attacker if the page contains user input: http://security.stackexchange.com/a/102015/12208

func CompressHandlerLevel

func CompressHandlerLevel(h http.Handler, level int) http.Handler

CompressHandlerLevel gzip compresses HTTP responses with specified compression level for clients that support it via the 'Accept-Encoding' header.

The compression level should be gzip.DefaultCompression, gzip.NoCompression, or any integer value between gzip.BestSpeed and gzip.BestCompression inclusive. gzip.DefaultCompression is used in case of invalid compression level.

func Handle

func Handle(pattern string, handler Handler, interceptors ...Interceptor)

Handle registers the handler for the given pattern. See http.ServeMux for a description of the pattern format.

func HandleFunc

func HandleFunc(pattern string, fct HandleFunction, interceptors ...Interceptor)

HandleFunc registers the handler function for the given pattern. See http.ServeMux for a description of the pattern format.

func HostOnly

func HostOnly(address string) string

HostOnly returns the host part of an address, without the port.

func MakeSessionId

func MakeSessionId() (string, error)

MakeSessionId create a new session id.

This is a low level function, made available for tests.

func NewSession

func NewSession(st gs.Store, opts *gs.Options, answer *SessionAnswer, user User) (session *gs.Session)

NewSession creates a new session for the given user.

This is a low level function, made available for tests. Use SendLoginAccepted instead.

func NewUnloggedUser

func NewUnloggedUser(st gs.Store, opts *gs.Options, user User) (session *gs.Session)

NewUnloggedUser creates a new unlogged session for the given anonymous user.

This is a low level function, made available for tests. Use SendUnloggedId instead.

func SessionKeys

func SessionKeys() [][]byte

SessionKeys retrieves the session keys for test purpose.

This is a low level function, made available for tests.

func Start

func Start() error

Start the server. Parameters are taken from the configuration.

func URLPortWithDefault

func URLPortWithDefault(url *url.URL) (port string)

URLPortWithDefault returns the port part of url.Host, without the leading colon. If url does not have a port, a default value is guessed from url.Scheme.

Types

type HandleFunction

type HandleFunction = func(ctx context.Context, response Response, request *Request)

HandleFunction is the signature of the functions that are called to handle requests.

type Handler

type Handler interface {
	Handle(ctx context.Context, response Response, request *Request)
}

A Handler responds to an HTTP request.

The Handle method should read the Request then use Response's methods to send the response. The Context must be checked for completion and transmitted to all called functions. The Context also contain a slog.Stacked that can be retrieved using slog.CtxLoadStacked.

As a convenience, if the Handle method panics with an HttpError then that error is send as response.

type HandlerFunc

type HandlerFunc HandleFunction

HandlerFunc wraps a function into a Handler.

func (HandlerFunc) Handle

func (self HandlerFunc) Handle(ctx context.Context, response Response, request *Request)

type HandlerWrapper

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

HandlerWrapper wraps a Handler into an http.Handler.

func NewHandlerWrapper

func NewHandlerWrapper(pattern string, handler Handler) HandlerWrapper

func (HandlerWrapper) Exec

func (self HandlerWrapper) Exec(ctx context.Context, response Response, request *Request)

Exec executes the underlying Handler. This method handles HttpError panics and turn them into call to response.SendError. This is a low-level method, to be used with caution, mainly in tests.

func (HandlerWrapper) MakeParams

func (self HandlerWrapper) MakeParams(wr http.ResponseWriter,
	original *http.Request) (ctx context.Context, resp Response, request *Request)

MakeParams converts http.Handler parameters into Handler parameters. This is a low-level method, to be used with caution, mainly in tests.

func (HandlerWrapper) ServeHTTP

func (self HandlerWrapper) ServeHTTP(wr http.ResponseWriter, original *http.Request)

ServeHTTP implements http.Handler.

type HttpError

type HttpError struct {
	// HTTP status code for the error.
	Code int

	// Message to send in the response.
	Msg string
	// contains filtered or unexported fields
}

A HttpError is an error that can be send as an HTTP response.

func InternalHttpError

func InternalHttpError(err error) HttpError

InternalHttpError wraps another error into an InternalServerError HttpError. This function is particularly usefull to panic inside an Handler, see Handler.

func NewHttpError

func NewHttpError(code int, msg string, detail string) HttpError

NewHttpError constructs a new HttpError.

The code is to be sent as the HTTP code of the response. It should be a constant from the net/http package. The message (msg) is to be sent as body of the HTTP response. This is the public description of the error. The detail is the private description of the error, to be displayed in the logs.

func UnauthorizedHttpError

func UnauthorizedHttpError(detail string) HttpError

UnauthorizedHttpError creates a preformatted HttpError notifying unauthorized request.

func WrapError

func WrapError(code int, msg string, err error) HttpError

WrapError wraps an error into an HttpError. Detail of the resulting error is the Error() message of the wrapped error.

func WrapUnauthorizedError

func WrapUnauthorizedError(err error) HttpError

WrapUnauthorizedError wrap an error into a preformatted HttpError notifying unauthorized request.

func (HttpError) Error

func (self HttpError) Error() string

func (HttpError) Unwrap

func (self HttpError) Unwrap() error

type Interceptor

type Interceptor = alice.Constructor

Interceptor is a function that takes a http.Handler and returns a http.Handler. Value of this type are sometimes called "http middleware".

type Request

type Request struct {
	// User is the session user.
	// It is nil if no user is successfully logged in the current session.
	User *User

	// SessionError is the error raised when checking the session informations send by the client.
	// It is nil either if the client did not send any session information (in which case User is nil
	// too) or if the session has been successfully checked (in which case Use is not nil).
	SessionError error

	// FullPath contains all path elements of the request made by the client.
	FullPath []string

	// RemainingPath contains the path elements after the pattern corresponding to the current
	// Handler.
	RemainingPath []string
	// contains filtered or unexported fields
}

A request represents an HTTP request to be handled by the server.

func (*Request) CheckPOST

func (self *Request) CheckPOST(ctx context.Context) error

CheckPOST ensures that the request is particularly safe.

This method returns nil only if the method is POST and there is an Origin header with the correct host.

func (*Request) RemoteAddr

func (self *Request) RemoteAddr() string

func (*Request) UnmarshalJSONBody

func (self *Request) UnmarshalJSONBody(dst interface{}) (err error)

UnmarshalJSONBody retrieves the body of the request as a JSON object. Successive calls to this method on the same object store identical objects. See json.Unmarshal for details of the unmarshalling process.

type Response

type Response interface {
	// SendJSON sends a JSON as response.
	// On success statuc code is http.StatusOK.
	SendJSON(ctx context.Context, data interface{})

	// SendError sends an error as response.
	// If the error is an HttpError, its code and msg are used in the HTPP response.
	// Also log the error.
	SendError(context.Context, error)

	// SendRedirect sends a permanent redirection.
	SendRedirect(ctx context.Context, req *Request, url string)

	// SendLoginAccepted create new credential for the user and send it as response.
	SendLoginAccepted(ctx context.Context, usr User, req *Request, profileInfo interface{})

	// SendUnloggedId adds a cookie for unlogged users.
	SendUnloggedId(ctx context.Context, user User, req *Request) error
}

Response is used to construct the response to a HTTP request.

type SessionAnswer

type SessionAnswer struct {
	SessionId string
	Expires   time.Time
	Profile   interface{}
}

SessionAnswer is the type of the value sent by request creating a new session. It is a part of the API between the server and the frontend.

Profile is not defined in this package. It must contains information about the user corresponding to the session. For security reason, Profile must not contain the user name, id, hash or password.

type User

type User struct {
	Id   uint32
	Name string
	Hash uint32

	// If Logged is true then Name is meaningfull else Hash is meaningfull.
	Logged bool
}

User represents a logged user.

Directories

Path Synopsis
Package servertest provides methods and types to test server.Handler implementations.
Package servertest provides methods and types to test server.Handler implementations.

Jump to

Keyboard shortcuts

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