Documentation
¶
Overview ¶
goh = Go Http Handlers.
Utility types that represent a not-yet-sent HTTP response as a value (status, header, body) with NO added abstractions. All types implement `http.Hander`.
See `readme.md` for examples.
Index ¶
- Constants
- Variables
- func Handler(fun func() http.Handler) (out http.Handler)
- func MutateHeader(tar, src http.Header)
- func Respond(rew http.ResponseWriter, req *http.Request, fun func() http.Handler)
- func WriteErr(rew http.ResponseWriter, _ *http.Request, err error, wrote bool)
- type AllowDirs
- type Bytes
- type Dir
- func (self Dir) Allow(path string) bool
- func (self Dir) File(path string) File
- func (self Dir) Han(req *http.Request) http.Handler
- func (self Dir) HanOpt(req *http.Request) http.Handler
- func (self Dir) Resolve(req *http.Request) File
- func (self Dir) ServeHTTP(rew http.ResponseWriter, req *http.Request)
- func (self Dir) ServedHTTP(rew http.ResponseWriter, req *http.Request) bool
- type ErrFunc
- type File
- func (self File) Existing() (_ File)
- func (self File) Exists() bool
- func (self File) Han(*http.Request) http.Handler
- func (self File) HanOpt(*http.Request) http.Handler
- func (self File) ServeHTTP(rew http.ResponseWriter, req *http.Request)
- func (self File) ServedHTTP(rew http.ResponseWriter, req *http.Request) bool
- type Filter
- type FilterFunc
- type Han
- type HttpHandlerOpt
- type Json
- type NotFound
- type Reader
- type Redirect
- type String
- type Xml
- type XmlDoc
Constants ¶
const ( HeadType = `Content-Type` TypeJson = `application/json` TypeXml = `application/xml` TypeForm = `application/x-www-form-urlencoded` TypeMulti = `multipart/form-data` )
Variables ¶
var HandleErr = WriteErr
Default error handler, used by various `http.Handler` types in this package when no `.ErrFunc` was provided. May be overridden globally.
Functions ¶
func Handler ¶ added in v0.1.3
Runs the provided function, returning the resulting `http.Handler`. Catches panics and converts them to a simple error responder via `Err`.
func MutateHeader ¶ added in v0.1.12
func Respond ¶ added in v0.1.3
Shortcut for serving the response generated by the provided function. Catches panics, serving the resulting errors as plain text via `Err`.
func WriteErr ¶ added in v0.1.9
Default implementation of `goh.ErrFunc`. Used by `http.Handler` types, such as `goh.String`, when no `goh.ErrFunc` was provided by user code. If possible, writes the error to the response writer as plain text. If not, logs the error to the standard error stream. When implementing a custom error handler, use this function's source as an example.
Types ¶
type AllowDirs ¶ added in v0.1.7
type AllowDirs []string
Implements `goh.Filter` by requiring that the input path is contained within one of the given directories. "Contained" means it begins with the directory path followed by a path separator.
type Bytes ¶
HTTP handler that writes bytes. Note: for sending a string, use `goh.String`, avoiding a bytes-to-string conversion.
func TryJsonBytes ¶ added in v0.1.8
func TryJsonBytes(val interface{}) Bytes
Shortcut for `goh.JsonOk(val).TryBytes()`. Should be used for pre-encoded handlers defined as global variables. Should NOT be used for dynamically-generated responses.
type Dir ¶ added in v0.1.7
HTTP handler that serves files out of a given directory. Similar to `http.FileServer`, but without its undesirable "smarts". This will serve only individual files, without directory listings or redirects. In addition, the method `goh.Dir.HanOpt` supports "try file" functionality, allowing you to fall back on serving something else when a requested file is not found.
The status, header, and err func are copied to each `goh.File` used for each response. Because this uses `goh.File` for each request, it doesn't support automatically adding headers such as `Content-Type`. See the comment on `goh.File`.
func (Dir) HanOpt ¶ added in v0.1.11
Conforms to `goh.Han`. Returns nil if the requested file is not found.
func (Dir) ServeHTTP ¶ added in v0.1.7
func (self Dir) ServeHTTP(rew http.ResponseWriter, req *http.Request)
Implement `http.Handler`.
func (Dir) ServedHTTP ¶ added in v0.1.11
Implement `HttpHandlerOpt`. If possible, serves the requested file and returns true. Otherwise returns false.
type ErrFunc ¶
Signature of an error handler function provided by user code to the various `http.Handler` types in this library, such as `String`. When nil, `goh.HandleErr` is used.
The `wrote` parameter indicates whether the response writer has been written to. If `false`, the handler should write an error response. If `true`, or if sending the error response has failed, the handler should log the resulting error to the server log.
type File ¶ added in v0.1.7
HTTP handler that always serves a file at a specific FS path. For each request, it verifies that the file exists and delegates to `http.ServeFile`. If the file doesn't exist, this responds with 404 without calling `http.ServeFile`, avoiding its undesirable "smarts".
Unlike `http.ServeFile` and `http.FileServer`, this does not automatically add headers such as `Content-Type`, `Last-Modified`, `Etag`, and so on. This tool is intended mostly for development or as a lower-level building block. For serving files in production, you're expected to use a dedicated file server, or a higher-level tool.
Unlike `http.ServeFile` and `http.FileServer`, responding with 404 is optional. `goh.File.HanOpt` returns a nil handler if the file is not found. You can use this to "try" serving a file, and fall back on something else.
func (File) Existing ¶ added in v0.1.11
If `.Exists()`, returns itself as-is. Otherwise returns zero. Example usage: `File{...}.Existing().Path`.
func (File) HanOpt ¶ added in v0.1.11
Conforms to `goh.Han`. Returns self if file exists, otherwise returns nil. Can be used to "try" serving a file.
func (File) ServeHTTP ¶ added in v0.1.7
func (self File) ServeHTTP(rew http.ResponseWriter, req *http.Request)
Implement `http.Handler`.
func (File) ServedHTTP ¶ added in v0.1.11
Implement `HttpHandlerOpt`. If `.Exists()`, uses `.ServeHTTP` to serve the file and returns true. Otherwise returns false.
type Filter ¶ added in v0.1.7
Used by `goh.Dir` to allow or deny serving specific paths. The input to `.Allow` is a normalized filesystem path that uses Unix-style forward slashes on both Unix and Windows. The path starts with `goh.Dir.Path`. For example:
dir := goh.Dir{Path: `static`}
req := &http.Request{URL: &url.URL{Path: `/some_file`}}
dir.Han(req)
->
dir.Filter.Allow(`static/some_file`)
type FilterFunc ¶ added in v0.1.7
Function type that implements `goh.Filter`. Example usage:
goh.Dir{Path: `.`, Filter: goh.FilterFunc(regexp.MustCompile(`^status/`))}
func (FilterFunc) Allow ¶ added in v0.1.7
func (self FilterFunc) Allow(val string) bool
Implement `goh.Filter` by calling itself.
type Han ¶ added in v0.1.8
Signature of a "request->response" function. All Goh handler types have a method `.Han` that conforms to this signature.
type HttpHandlerOpt ¶ added in v0.1.11
type HttpHandlerOpt interface {
ServedHTTP(http.ResponseWriter, *http.Request) bool
}
Variant of `http.Handler` that may or may not serve the request. If capable of serving the request, must serve it and return true. Otherwise, must return false without any side effects in the given response writer and request. This interface is implemented by some types in this module.
type Json ¶
HTTP handler that automatically sets the appropriate JSON headers and encodes its body as JSON. The field `.Indent` is passed to the JSON encoder.
func (Json) ServeHTTP ¶
func (self Json) ServeHTTP(rew http.ResponseWriter, req *http.Request)
Implement `http.Handler`.
func (Json) TryBytes ¶ added in v0.1.5
Converts to `goh.Bytes` by encoding the body and adding the appropriate content type header. Panics on encoding errors. Should be used in root scope to pre-encode a static response:
import "github.com/mitranim/goh" var someHan = goh.JsonOk(someValue).TryBytes()
type NotFound ¶ added in v0.1.7
type NotFound struct{}
Zero-sized handler that returns with 404 without any additional headers or body content. Used internally by `goh.File`.
type Reader ¶
HTTP handler that copies a response from a reader.
Caution: if the reader is also `io.Closer`, it must be closed in your code. This type does NOT attempt that.
type Redirect ¶
HTTP handler that performs an HTTP redirect.
func RedirectWith ¶
Shortcut for `goh.Redirect` with specific status and body.
type String ¶
HTTP handler that writes a string. Note: for sending bytes, use `goh.Bytes`, avoiding a string-to-bytes conversion.
func Err ¶ added in v0.1.3
Makes an extremely simple `http.Handler` that serves the error's message as plain text. The status is always 500.
func StringWith ¶
Shortcut for `goh.String` with specific status and body.
type Xml ¶
type Xml Json
HTTP handler that automatically sets the appropriate XML headers and encodes its body as XML. The field `.Indent` is passed to the JSON encoder.
Caution: this does NOT prepend the processing instruction `<?xml?>`. When you don't need to specify the encoding, this instruction is entirely skippable. When you need to specify the encoding, wrap `.Body` in the utility type `goh.XmlDoc` provided by this package.
func (Xml) ServeHTTP ¶
func (self Xml) ServeHTTP(rew http.ResponseWriter, req *http.Request)
Implement `http.Handler`.
type XmlDoc ¶ added in v0.1.1
type XmlDoc struct {
Encoding string
Val interface{}
}
Utility type for use together with `goh.Xml`. When encoded as XML, this prepends the `<?xml?>` header with version 1.0 and the specified encoding, if any. Example usage:
myXmlDoc := SomeType{SomeField: someValue}
res := goh.XmlOk(goh.XmlDoc{
Encoding: "utf-8",
Val: myXmlDoc,
})
Eventual output:
<?xml version="1.0" encoding="utf-8"?> <SomeType ...>
func (XmlDoc) MarshalXML ¶ added in v0.1.1
Implement `encoding/xml.Marshaler`, prepending the `<?xml?>` processing instruction, with the specified encoding if available.