Documentation
¶
Index ¶
- Constants
- Variables
- func CacheBustedPath(url string) string
- func DisableOutputBuffering(ctx context.Context)
- func GetAssetUrl(location string) string
- func MakeLocalPath(p string) string
- func OutputLen(ctx context.Context) int
- func ParseAuthorizationHeader(auth string) (scheme, params string)
- func ParseJsonBody(w http.ResponseWriter, r *http.Request, maxBytes int64, dest any) error
- func ParseValueAndParams(in string) (value string, params map[string]string)
- func Redirect(location string, errCode int)
- func RegisterAppHandler(pattern string, handler http.Handler)
- func RegisterAssetDirectory(prefix string, fsys fs.FS)
- func RegisterContentType(extension string, contentType string)
- func RegisterDrawFunc(pattern string, f DrawFunc)
- func RegisterFileProcessor(extension string, processorFunc FileProcessorFunc)
- func RegisterStaticHandler(pattern string, handler http.Handler)
- func ResetOutputBuffer(ctx context.Context) []byte
- func SendBadRequest()
- func SendBadRequestMessage(message string)
- func SendErrorCode(errCode int)
- func SendErrorMessage(message string, errCode int)
- func SendForbidden()
- func SendForbiddenMessage(m string)
- func SendJsonAuthenticateError(errCode int, authScheme string, values map[string]string)
- func SendMethodNotAllowed(allowedMethods ...string)
- func SendNotFound()
- func SendNotFoundMessage(message string)
- func SendUnauthorized()
- func SendUnauthorizedMessage(message string)
- func SetLocalPathMaker(f LocalPathMaker)
- func StripCacheBusterPath(fPath string) string
- func ValidateHeader(header http.Header) bool
- func WithAppMuxer(next http.Handler) http.Handler
- func WithBufferedOutput(next http.Handler) http.Handler
- func WithErrorHandler(h http.Handler) http.Handler
- func WithHeaderValidator(next http.Handler) http.Handler
- func WithMuxer(mux Muxer, next http.Handler) http.Handler
- func WithPatternMuxer(next http.Handler) http.Handler
- func WriteHstsHeader(w http.ResponseWriter, maxAge int64, includeSubDomains bool, preload bool)
- type BufferedResponseWriterI
- type DrawFunc
- type Error
- type ErrorReporter
- type FileProcessorFunc
- type FileSystemServer
- type LocalPathMaker
- type Muxer
- type ServerError
- type User
Constants ¶
const BrotliSuffix = ".br"
const GZipSuffix = ".gz"
Variables ¶
var MaxErrorStackDepth = 20
MaxErrorStackDepth is the maximum stack depth reported to the error log when a panic happens.
Functions ¶
func CacheBustedPath ¶
CacheBustedPath returns a path to an asset that was previously registered with the CacheBuster. The new path will contain a hash of the file that will change whenever the file changes, and cause the browser to reload the file. Since we are in control of serving these files, we will later remove the hash before serving it.
func DisableOutputBuffering ¶
DisableOutputBuffering turns off output buffering.
This function is useful if you want to stream large quantities of data to the response writer, and you want to avoid the memory allocation required for buffering. The default output buffer manager will not output what has been buffered so far. You should not try to re-enable output buffering.
func GetAssetUrl ¶
GetAssetUrl returns the url that corresponds to the asset at the given path.
This will add the cache-buster path, and the proxy path if there is one.
func MakeLocalPath ¶
MakeLocalPath turns a path that points to a resource on this computer into a path that will reach that resource from a browser. It takes into account a variety of settings that may affect the path and that will depend on how the app is deployed. You can inject your own local path maker using SetLocalPathMaker
func OutputLen ¶
OutputLen returns the number of bytes written to the output.
If output buffering is disabled, this will be the number of bytes actually written to the response writer. If output buffering is enabled, this is the number of bytes in the buffer waiting to be sent.
func ParseAuthorizationHeader ¶
ParseAuthorizationHeader will parse an authorization header into its scheme and params.
func ParseJsonBody ¶
ParseJsonBody will look for json in the request, parse it into the given dest, and handle errors.
The dest should be a pointer to a structure or some other value you want filled with the data. Errors will result in an appropriate error response written to the response writer, and an error response. If maxBytes is reached, it will close the connection and error.
func ParseValueAndParams ¶
ParseValueAndParams returns the value and param map for Content-Type and Content-Disposition header values.
func Redirect ¶
Redirect will error such that the server will attempt to access the resource at a new location.
This will set the Location header to point to the new location.
errCode should be a 3XX error, like one of the following:
StatusMovedPermanently = 301 // RFC 7231, 6.4.2 StatusFound = 302 // RFC 7231, 6.4.3 StatusSeeOther = 303 // RFC 7231, 6.4.4 StatusTemporaryRedirect = 307 // RFC 7231, 6.4.7 StatusPermanentRedirect = 308 // RFC 7538, 3
func RegisterAppHandler ¶
RegisterAppHandler registers a handler for the given pattern.
Use this when registering a handler to a specific path. Use RegisterAppPrefixHandler if registering a handler for a whole subdirectory of a path.
The given handler is served near the end of the application handler stack, so you will have access to session management and any other middleware handlers in the application stack.
You may call this from an init() function.
func RegisterAssetDirectory ¶
RegisterAssetDirectory maps a file system to a URL path in the application.
The files in the path are registered with the cache buster, so that when you edit the file a new URL will be generated forcing the browser to reload the asset. This is much better than using a cache control header.
If the browser attempts to access a file in the file system that does not exist, a 404 NotFound error will be sent back to the browser.
func RegisterContentType ¶
RegisterContentType registers a content type that associates a file extension with a specific content type. You do not need to do this for all content served, as Go's http handler will try to guess the content type by the name of the file or the content itself. This is for those situations where Go's default is not working.
The extension must begin with a dot and have only one dot in it.
func RegisterDrawFunc ¶
RegisterDrawFunc registers an output function for the given pattern.
This could be used to register template output with a path, for example. See the renderResource template macro and the configure.tpl.got file in the welcome application for an example.
The file name extension will be used first to determine the Content-Type. If that fails, then the content will be inspected to determine the Content-Type.
Registered handlers are served by the AppMuxer.
func RegisterFileProcessor ¶
func RegisterFileProcessor(extension string, processorFunc FileProcessorFunc)
RegisterFileProcessor registers a processor function for static files that have a particular extension. Do this at init time. The extension must begin with a dot and only have one dot in it.
func RegisterStaticHandler ¶
RegisterStaticHandler registers a handler for the given pattern.
The given handler is served immediately by the application without going through the application handler stack. If you need session management, HSTS protection, authentication, etc., use RegisterAppHandler.
If a ProxyPath is set, it will automatically be inserted in front of the path in the pattern. If the pattern has a path that ends in "/"
func ResetOutputBuffer ¶
ResetOutputBuffer returns the current output buffer and resets the output buffer to nothing.
func SendBadRequest ¶
func SendBadRequest()
SendBadRequest sends a StatusBadRequest code to the output.
func SendBadRequestMessage ¶
func SendBadRequestMessage(message string)
SendBadRequestMessage sends a StatusBadRequest code to the output with a message.
func SendErrorCode ¶
func SendErrorCode(errCode int)
SendErrorCode will cause the page to error with the given http error code.
func SendErrorMessage ¶
SendErrorMessage sends the error message with the http code to the browser.
func SendForbidden ¶
func SendForbidden()
SendForbidden will tell the user that he/she does not have authorization to access the given resource. The user should be known.
func SendForbiddenMessage ¶
func SendForbiddenMessage(m string)
SendForbiddenMessage will tell the user that he/she does not have authorization to access the given resource. The user should be known.
func SendJsonAuthenticateError ¶
SendJsonAuthenticateError sends a WWW-Authenticate error encoding the values into both the WWW-Authenticate header and as a json response
func SendMethodNotAllowed ¶
func SendMethodNotAllowed(allowedMethods ...string)
SendMethodNotAllowed will tell the user that the server is not able to perform the http method being asked. allowedMethods is a list of the allowed methods.
func SendNotFoundMessage ¶
func SendNotFoundMessage(message string)
SendNotFoundMessage sends a StatusNotFound with a message.
func SendUnauthorized ¶
func SendUnauthorized()
SendUnauthorized will send an error code indicating that the user is not authenticated (yes, even though the title is "authorized", it really means "authenticated", i.e. not logged in.) If serving HTML, you likely should redirect to the login page instead.
func SendUnauthorizedMessage ¶
func SendUnauthorizedMessage(message string)
SendUnauthorizedMessage will send an error code indicating that the user is not authenticated (yes, even though the title is "authorized", it really means "authenticated", i.e. not logged in.) If serving HTML, you likely should redirect to the login page instead.
func SetLocalPathMaker ¶
func SetLocalPathMaker(f LocalPathMaker)
SetLocalPathMaker sets the local path maker to the given one.
The default local path maker will prepend config.ProxyPath to all local paths.
func StripCacheBusterPath ¶
StripCacheBusterPath removes the hash of the asset file from the path to the asset.
func ValidateHeader ¶
ValidateHeader confirms that the given header's values only contains ASCII characters.
func WithAppMuxer ¶
WithAppMuxer serves up the AppMuxer.
func WithBufferedOutput ¶
WithBufferedOutput is middleware that adds output buffering to the handler stack. Output buffering lets you build the output over multiple write calls, but does not send the output until writing is complete. If an error occurs, this lets you send a nice error message, rather than a half finished output.
func WithErrorHandler ¶
WithErrorHandler is middleware that inserts an error catcher into the handler stack that will catch downstream panics and prevent them from the stopping the server. They will instead be reported to the structured logger, and also be send a message to the browser in coordination with the goradd javascript.
Panic with an http.Error value to get a specific kind of http error to be output. Otherwise, errors will be sent to the log.Error logger.
func WithHeaderValidator ¶
WithHeaderValidator insert middleware into the handler stack that performs OWASP style validation on a request.
func WithMuxer ¶
WithMuxer serves a muxer such that if a handler cannot be found, or the found handler does not respond, control is past to the next handler.
Be careful using the standard Go Muxer, as it improperly handles redirects if this is behind a reverse proxy.
func WithPatternMuxer ¶
WithPatternMuxer serves up the PatternMuxer.
func WriteHstsHeader ¶
func WriteHstsHeader(w http.ResponseWriter, maxAge int64, includeSubDomains bool, preload bool)
WriteHstsHeader writes an HSTS header to w, which will cause the browser to enforce HTTPS by redirecting http requests to port 443 over https.
maxAge is in seconds. A value of zero will disable hsts. includeSubDomains will cause attempts at contacting subdomains over http to also redirect to https. preload signals intent to be included in Google's special universal preload domain list.
Types ¶
type BufferedResponseWriterI ¶
type BufferedResponseWriterI interface {
http.ResponseWriter
Disable()
OutputBuffer() *bytes.Buffer
Len() int
}
BufferedResponseWriterI is the interface for a BufferedResponseWriter.
type DrawFunc ¶
A DrawFunc sends output to the Writer. goradd uses this signature in its template functions.
type Error ¶
Error represents an error response to an http request.
See http.Status* codes for status code constants
func (Error) SetAuthenticateError ¶
SetAuthenticateError sets the WWW-Authenticate with the given authScheme and values.
func (*Error) SetResponseHeader ¶
SetResponseHeader sets a key-value in the header response.
type ErrorReporter ¶
type ErrorReporter struct {
}
ErrorReporter is a middleware that will catch panics and other errors and convert them to http output messages. It also logs panics to the error logger.
type FileProcessorFunc ¶
FileProcessorFunc processes a static file and outputs it to the response writer.
type FileSystemServer ¶
type FileSystemServer struct {
// Fsys is the file system being served.
Fsys fs.FS
// SendModTime will send the modification time of the file when it is served. Generally, you want
// to do this for files that can be bookmarked, like html files, since there really is no other way
// to try to get the server to reload the file when it is changed. However, for asset files that are
// using the cache buster, you should not do this, since cache busting will take care of notifying
// the user the file is changed.
SendModTime bool
// UseCacheBuster will look for cache buster paths and fix them.
UseCacheBuster bool
// Hide is a slice of file endings that will be blocked from being served. These endings do not have to just
// be file extensions, but any string. So if you specify an ending of "_abc.txt", any file ending in the
// string will NOT be shown.
Hide []string
}
func (FileSystemServer) ServeHTTP ¶
func (f FileSystemServer) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP will serve the file system.
type LocalPathMaker ¶
LocalPathMaker converts an HTTP path rooted to the application, to a path accessible by the server.
type Muxer ¶
type Muxer interface {
// Handle associates a handler with the given pattern in the url path
Handle(pattern string, handler http.Handler)
// Handler returns the handler associate with the request, if one exists. It
// also returns the actual path registered to the handler
Handler(r *http.Request) (h http.Handler, pattern string)
// ServeHTTP sends a request to the MUX, to be forwarded on to the registered handler,
// or responded with an unknown resource error.
ServeHTTP(w http.ResponseWriter, r *http.Request)
}
Muxer represents the typical functions available in a mux and allows you to replace the default muxer here with a 3rd party mux.
However, beware. The default Go muxer will do redirects. If the application is behind a reverse proxy that is rewriting the url, the Go muxer will not correctly do rewrites because it will not include the reverse proxy path in the rewrite rule, and things will break.
If you create your own mux and you want to do redirects, use MakeLocalPath to create the redirect url. See also maps.SafeMap for a map you can use if you are modifying paths while using the mux.
var AppMuxer Muxer = http.NewServeMux()
AppMuxer is the application muxer that lets you do http handling from behind the application facilities of session management, output buffering, etc.
var PatternMuxer Muxer = http.NewServeMux()
PatternMuxer is the muxer that immediately routes handlers based on the path without going through the application handlers. It responds directly to the ResponseWriter.
type ServerError ¶
type ServerError struct {
// the error string
Err string
// Mode indicates whether we are serving ajax or not
Mode string
// the time the error occurred
Time time.Time
Request *http.Request
// Output will replace what gets written to the output
Output string
// How much additional to unwind the stack trace
StackDepth int
}
ServerError represents an error caused by an unexpected panic
func NewServerError ¶
func NewServerError(err string, mode string, r *http.Request, skipFrames int, output string) *ServerError
NewServerError creates a new ServerError.
func (ServerError) Error ¶
func (s ServerError) Error() string
Error returns the string that is sent to the logger