Documentation
¶
Index ¶
- func CombinedLoggingHandler(logger logutil.ContextLogger, h http.Handler) http.Handler
- func CompressorFileServer(config *CompressorFileServerConfig, root http.FileSystem) http.Handler
- func CustomLoggingHandler(logger logutil.ContextLogger, h http.Handler, f LogFormatter) http.Handler
- func HasContentType(r *http.Request, mimetype string) bool
- func JsonSetEscapeHtml(on bool)
- func LoggingHandler(logger logutil.ContextLogger, h http.Handler) http.Handler
- func WriteError(writer http.ResponseWriter, err error, code int)
- func WriteErrorHtmlEscape(writer http.ResponseWriter, err error, code int, htmlEscape bool)
- func WriteErrorObj(writer http.ResponseWriter, obj interface{}, err error, code int)
- func WriteErrorObjHtmlEscape(writer http.ResponseWriter, obj interface{}, err error, code int, ...)
- func WriteObj(writer http.ResponseWriter, obj interface{}, code int) (err error)
- func WriteObj200(writer http.ResponseWriter, obj interface{}) (err error)
- func WriteObj200HtmlEscape(writer http.ResponseWriter, obj interface{}, htmlEscape bool) (err error)
- func WriteObjHtmlEscape(writer http.ResponseWriter, obj interface{}, code int, htmlEscape bool) (err error)
- type BrotliCompressorEncoder
- type BrotliResponseWriter
- type CompressorFileServerConfig
- type GzipResponseWriter
- type HttpStatusRecorder
- type LogFormatter
- type LogFormatterParams
- type LzwResponseWriter
- type ServerManager
- func (manager *ServerManager) BatchSpawnHttp(listenAddresses []string, handler http.Handler)
- func (manager *ServerManager) BatchSpawnHttps(listenAddresses []string, handler http.Handler, certFile, keyFile string)
- func (manager *ServerManager) Err() error
- func (manager *ServerManager) Shutdown()
- func (manager *ServerManager) SpawnHttp(listenAddress string, handler http.Handler)
- func (manager *ServerManager) SpawnHttpTls(listenAddress string, handler http.Handler, certFile, keyFile string)
- func (manager *ServerManager) Wait()
- type ZlibResponseWriter
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CombinedLoggingHandler ¶
CombinedLoggingHandler return a http.Handler that wraps h and logs requests to out in Apache Combined Log Format.
See http://httpd.apache.org/docs/2.2/logs.html#combined for a description of this format.
LoggingHandler always sets the ident field of the log to -.
func CompressorFileServer ¶
func CompressorFileServer(config *CompressorFileServerConfig, root http.FileSystem) http.Handler
CompressorFileServer creates another variant of http.FileServer which supports compression. It does not however support byte range (Accept-Ranges header), in which it will just use the normal http.FileServer and compression is disabled altogether.
When compression is enabled, Content-Length header will be removed.
func CustomLoggingHandler ¶
func CustomLoggingHandler(logger logutil.ContextLogger, h http.Handler, f LogFormatter) http.Handler
CustomLoggingHandler provides a way to supply a custom log formatter while taking advantage of the mechanisms in this package.
func HasContentType ¶
HasContentType determines whether the request `content-type` includes a server-acceptable mime-type. Do not just compare Content-Type with == operator as the value may contain additional texts.
Failure should yield an HTTP 415 (`http.StatusUnsupportedMediaType`)
func JsonSetEscapeHtml ¶
func JsonSetEscapeHtml(on bool)
JsonSetEscapeHtml sets HTML escaping mode for WriteObj and other variants. This will turn json.Encoder HTML escaping on or off in this package.
func LoggingHandler ¶
LoggingHandler return a http.Handler that wraps h and logs requests to out in Apache Common Log Format (CLF).
See http://httpd.apache.org/docs/2.2/logs.html#common for a description of this format.
LoggingHandler always sets the ident field of the log to -
Example:
r := mux.NewRouter()
r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("This is a catch-all route"))
})
loggedRouter := handlers.LoggingHandler(os.Stdout, r)
http.ListenAndServe(":1123", loggedRouter)
func WriteError ¶
func WriteError(writer http.ResponseWriter, err error, code int)
WriteError writes a string of error as JSON. See also WriteErrorObj.
func WriteErrorHtmlEscape ¶
func WriteErrorHtmlEscape(writer http.ResponseWriter, err error, code int, htmlEscape bool)
WriteErrorHtmlEscape writes a string of error as JSON. See also WriteErrorObj.
func WriteErrorObj ¶
func WriteErrorObj(writer http.ResponseWriter, obj interface{}, err error, code int)
WriteErrorObj writes obj as response and send in HTTP error code. This is a helper function to marshal obj as JSON and send it together with error. Error will always be written in `error` JSON field.
func WriteErrorObjHtmlEscape ¶
func WriteErrorObjHtmlEscape(writer http.ResponseWriter, obj interface{}, err error, code int, htmlEscape bool)
WriteErrorObjHtmlEscape writes obj as response and send in HTTP error code. This is a helper function to marshal obj as JSON and send it together with error. Error will always be written in `error` JSON field.
func WriteObj ¶
func WriteObj(writer http.ResponseWriter, obj interface{}, code int) (err error)
WriteObj writes an object to the response writer as JSON. It also sets Content-Type to application/json and send in HTTP `code`. The `code` should be 2xx.
func WriteObj200 ¶
func WriteObj200(writer http.ResponseWriter, obj interface{}) (err error)
WriteObj200 writes an object with WriteObj and sends 200 code.
func WriteObj200HtmlEscape ¶
func WriteObj200HtmlEscape(writer http.ResponseWriter, obj interface{}, htmlEscape bool) (err error)
WriteObj200HtmlEscape writes an object with WriteObj and sends 200 code. It has option to override JSON encoding HTML escape.
func WriteObjHtmlEscape ¶
func WriteObjHtmlEscape(writer http.ResponseWriter, obj interface{}, code int, htmlEscape bool) (err error)
WriteObjHtmlEscape writes an object to the response writer as JSON. It also sets Content-Type to application/json and send in HTTP `code`. The `code` should be 2xx.
It has option to override JSON encoding HTML escape.
Types ¶
type BrotliCompressorEncoder ¶
type BrotliCompressorEncoder interface {
io.WriteCloser
Flush() error
}
BrotliCompressorEncoder is a custom compressor. This is used to supply a custom Brotli encoder. It is designed this way so go-httputil does not depend on the cbrotli library which requires Brotli C headers and cgo.
type BrotliResponseWriter ¶
type BrotliResponseWriter struct {
http.ResponseWriter
// contains filtered or unexported fields
}
BrotliResponseWriter is a http.ResponseWriter which supports writing content with Brotli compression. This response writer does not care about the Accept-Encoding header, and will write Content-Encoding header immediately just before the first call of Write.
Compression headers are only sent before first call to write to be able to disable compression in case content type and length are outside the defined parameters. The response writer checks if Content-Type and Content-Length headers were set before the first call to Write to see the type and length of the content sent.
This response writer requires closing, so it must be closed after all writes have been completed.
func NewBrotliResponseWriter ¶
func NewBrotliResponseWriter(writer http.ResponseWriter, brotliEncoder BrotliCompressorEncoder, minLength int, contentTypes []string) *BrotliResponseWriter
NewBrotliResponseWriter creates a new compression response writer.
func (*BrotliResponseWriter) Close ¶
func (brw *BrotliResponseWriter) Close() error
Close closes this writer by flushing and sending the compression footer bytes.
func (*BrotliResponseWriter) Flush ¶
func (brw *BrotliResponseWriter) Flush()
func (*BrotliResponseWriter) Hijack ¶
func (brw *BrotliResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
func (*BrotliResponseWriter) Write ¶
func (brw *BrotliResponseWriter) Write(data []byte) (int, error)
Write writes data to response with compression (if compression can be enabled). First call to Write (or WriteHeader) will check if compression can be enabled. If not it will behave just like a normal http.ResponseWriter.
func (*BrotliResponseWriter) WriteHeader ¶
func (brw *BrotliResponseWriter) WriteHeader(statusCode int)
type CompressorFileServerConfig ¶
type CompressorFileServerConfig struct {
// Enables the "br" compression.
EnableBrotli bool
// Enables the "gzip" compression.
EnableGzip bool
// Enables the "deflate" compression.
EnableZlib bool
// Enables the "compress" compression.
EnableLzw bool
// Brotli encoder, you can use the cbrotli library (this requires cgo).
BrotliEncoder func(writer http.ResponseWriter) BrotliCompressorEncoder
// GZIP quality level: -1 to 9.
// -1 for default compression, 0 for no compression, 9 for maximum compression.
GzipQuality int
// ZLIB quality level: -1 to 9.
// -1 for default compression, 0 for no compression, 9 for maximum compression.
ZlibQuality int
// ContentTypes that are supported to be compressed.
// Empty will compress all.
ContentTypes []string
// The minimum length of the content that is going to be written for compression to be active.
MinLength int
IndexFiles []string
ErrorHandlers map[int]func(writer http.ResponseWriter, err error)
}
type GzipResponseWriter ¶
type GzipResponseWriter struct {
http.ResponseWriter
// contains filtered or unexported fields
}
GzipResponseWriter is a http.ResponseWriter which supports writing content with gzip compression. This response writer does not care about the Accept-Encoding header, and will write Content-Encoding header immediately just before the first call of Write.
Compression headers are only sent before first call to write to be able to disable compression in case content type and length are outside the defined parameters. The response writer checks if Content-Type and Content-Length headers were set before the first call to Write to see the type and length of the content sent.
This response writer requires closing, so it must be closed after all writes have been completed.
func NewGzipResponseWriter ¶
func NewGzipResponseWriter(writer http.ResponseWriter, level, minLength int, contentTypes []string) *GzipResponseWriter
NewGzipResponseWriter creates a new compression response writer.
func (*GzipResponseWriter) Close ¶
func (grw *GzipResponseWriter) Close() error
Close closes this writer by flushing and sending the compression footer bytes.
func (*GzipResponseWriter) Flush ¶
func (grw *GzipResponseWriter) Flush()
func (*GzipResponseWriter) Hijack ¶
func (grw *GzipResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
func (*GzipResponseWriter) Write ¶
func (grw *GzipResponseWriter) Write(data []byte) (int, error)
Write writes data to response with compression (if compression can be enabled). First call to Write (or WriteHeader) will check if compression can be enabled. If not it will behave just like a normal http.ResponseWriter.
func (*GzipResponseWriter) WriteHeader ¶
func (grw *GzipResponseWriter) WriteHeader(statusCode int)
type HttpStatusRecorder ¶
type HttpStatusRecorder struct {
http.ResponseWriter
Status int
BytesWritten int
}
HttpStatusRecorder implements the default http.ResponseWriter interface, used to record the returned HTTP status code.
func NewHttpStatusRecorder ¶
func NewHttpStatusRecorder(writer http.ResponseWriter) *HttpStatusRecorder
NewHttpStatusRecorder creates a HttpStatusRecorder (no http.Flusher, Hijacker, or Pusher interfaces).
func (*HttpStatusRecorder) Hijack ¶
func (rec *HttpStatusRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error)
func (*HttpStatusRecorder) Write ¶
func (rec *HttpStatusRecorder) Write(p []byte) (n int, err error)
func (*HttpStatusRecorder) WriteHeader ¶
func (rec *HttpStatusRecorder) WriteHeader(code int)
WriteHeader overrides the default WriteHeader behavior to also write access logs.
type LogFormatter ¶
type LogFormatter func(ctx context.Context, logger logutil.ContextLogger, params LogFormatterParams)
LogFormatter gives the signature of the formatter function passed to CustomLoggingHandler.
type LogFormatterParams ¶
type LogFormatterParams struct {
Request *http.Request
URL url.URL
TimeStamp time.Time
StatusCode int
Size int
}
LogFormatterParams is the structure any formatter will be handed when time to log comes. Taken and modified from Gorilla mux.
type LzwResponseWriter ¶
type LzwResponseWriter struct {
http.ResponseWriter
// contains filtered or unexported fields
}
LzwResponseWriter is a http.ResponseWriter which supports writing content with LZW ("compress") compression. This response writer does not care about the Accept-Encoding header, and will write Content-Encoding header immediately just before the first call of Write.
Compression headers are only sent before first call to write to be able to disable compression in case content type and length are outside the defined parameters. The response writer checks if Content-Type and Content-Length headers were set before the first call to Write to see the type and length of the content sent.
This response writer requires closing, so it must be closed after all writes have been completed.
func NewLzwResponseWriter ¶
func NewLzwResponseWriter(writer http.ResponseWriter, minLength int, contentTypes []string) *LzwResponseWriter
NewLzwResponseWriter creates a new compression response writer.
func (*LzwResponseWriter) Close ¶
func (lrw *LzwResponseWriter) Close() error
Close closes this writer by flushing and sending the compression footer bytes.
func (*LzwResponseWriter) Flush ¶
func (lrw *LzwResponseWriter) Flush()
func (*LzwResponseWriter) Hijack ¶
func (lrw *LzwResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
func (*LzwResponseWriter) Write ¶
func (lrw *LzwResponseWriter) Write(data []byte) (int, error)
Write writes data to response with compression (if compression can be enabled). First call to Write (or WriteHeader) will check if compression can be enabled. If not it will behave just like a normal http.ResponseWriter.
func (*LzwResponseWriter) WriteHeader ¶
func (lrw *LzwResponseWriter) WriteHeader(statusCode int)
type ServerManager ¶
type ServerManager struct {
Logger logutil.Logger // An instance of logutil.Logger for the manager to log to.
// TlsConfig defines a custom TLS config to be passed to TLS servers when started.
// It cannot be changed in runtime, so servers have to be restarted again.
TlsConfig *tls.Config
// contains filtered or unexported fields
}
The ServerManager controls HTTP and HTTPS servers that are deployed and listening to connections. It tracks and waits for all servers to shutdown (by invoking Wait), and can shuts down all servers at once by calling Shutdown. When one server cannot be launched, all the remaining servers are shut down.
To use the ServerManager, simply create the manager and spawn HTTP/HTTPS servers using SpawnHttp and SpawnHttps methods and you can expect the manager to control them for you. Right now there is no support for shutting down individual server.
func NewServerManager ¶
func NewServerManager() *ServerManager
NewServerManager creates a new ServerManager with the default logger. By default, it uses StdLogger with "ServerManager" as prefix. You can change it by changing the Logger.
func (*ServerManager) BatchSpawnHttp ¶
func (manager *ServerManager) BatchSpawnHttp(listenAddresses []string, handler http.Handler)
BatchSpawnHttp spawns a single HTTP TLS server using listenAddress and router as the primary Handler. See also SpawnHttp.
func (*ServerManager) BatchSpawnHttps ¶
func (manager *ServerManager) BatchSpawnHttps(listenAddresses []string, handler http.Handler, certFile, keyFile string)
BatchSpawnHttps spawns multiple HTTP TLS servers at once on each listenAddress. See also SpawnHttp.
func (*ServerManager) Err ¶
func (manager *ServerManager) Err() error
Err returns the last error that is encountered when spawning servers. Because spawning servers is an async process, Err() might not return an error immediately after the server is started. You might want to wait for a few seconds after spawning before checking on Err before stopping the whole server manager.
Example error: address already in use.
func (*ServerManager) Shutdown ¶
func (manager *ServerManager) Shutdown()
Shutdown sends a signal to ServerManager to shut all the servers down.
func (*ServerManager) SpawnHttp ¶
func (manager *ServerManager) SpawnHttp(listenAddress string, handler http.Handler)
SpawnHttp spawns a single HTTP server using listenAddress and router as the primary Handler. When the server encounters and error other than http.ErrServerClosed, it will tell the ServerManager to shut down. http.ErrServerClosed is emitted when the server is shut down, which means it is not a real error.
func (*ServerManager) SpawnHttpTls ¶
func (manager *ServerManager) SpawnHttpTls(listenAddress string, handler http.Handler, certFile, keyFile string)
SpawnHttpTls spawns multiple HTTP servers at once on each listenAddress. See also SpawnHttp.
func (*ServerManager) Wait ¶
func (manager *ServerManager) Wait()
Wait for all servers to finish all operations.
type ZlibResponseWriter ¶
type ZlibResponseWriter struct {
http.ResponseWriter
// contains filtered or unexported fields
}
ZlibResponseWriter is a http.ResponseWriter which supports writing content with zlib ("deflate") compression. This response writer does not care about the Accept-Encoding header, and will write Content-Encoding header immediately just before the first call of Write.
Compression headers are only sent before first call to write to be able to disable compression in case content type and length are outside the defined parameters. The response writer checks if Content-Type and Content-Length headers were set before the first call to Write to see the type and length of the content sent.
This response writer requires closing, so it must be closed after all writes have been completed.
func NewZlibResponseWriter ¶
func NewZlibResponseWriter(writer http.ResponseWriter, level, minLength int, contentTypes []string) *ZlibResponseWriter
func (*ZlibResponseWriter) Close ¶
func (zrw *ZlibResponseWriter) Close() error
Close closes this writer by flushing and sending the compression footer bytes.
func (*ZlibResponseWriter) Flush ¶
func (zrw *ZlibResponseWriter) Flush()
func (*ZlibResponseWriter) Hijack ¶
func (zrw *ZlibResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
func (*ZlibResponseWriter) Write ¶
func (zrw *ZlibResponseWriter) Write(data []byte) (int, error)
Write writes data to response with compression (if compression can be enabled). First call to Write (or WriteHeader) will check if compression can be enabled. If not it will behave just like a normal http.ResponseWriter.
func (*ZlibResponseWriter) WriteHeader ¶
func (zrw *ZlibResponseWriter) WriteHeader(statusCode int)