www

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2024 License: MIT Imports: 14 Imported by: 8

README

Go www package

www is a package to assist in writing HTTP servers.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var EnableRateLimiting bool

You can disable this when running unit tests

Functions

func CacheImmutable

func CacheImmutable(w http.ResponseWriter)

Set cache headers which indicate that this resource is immutable Apparently chrome is not going to implement the immutable cache-control tag, so we just set a long expiry date.

func CacheNever

func CacheNever(w http.ResponseWriter)

Set cache headers instructing the client never to cache

func CacheSeconds

func CacheSeconds(w http.ResponseWriter, seconds int)

Set cache headers for a given expiry in seconds

func Check

func Check(err error)

Check causes a panic if err is not nil.

func CheckClient

func CheckClient(err error)

CheckClient causes a PanicBadRequest if err is not nil.

func CheckLogged

func CheckLogged(l logs.Log, err error)

CheckLogged writes the error to the log, and then causes a panic, if err is not nil.

func Do

func Do(req *http.Request) (*http.Response, error)

Perform the request, and if any errors occurs (transport or non-200 status code), return an error This does the work for you of checking for a non-200 response, reading the response body, and turning it into an error.

func EncodeQuery

func EncodeQuery(kv map[string]string) string

EncodeQuery returns a key=value&key2=value2 string for a URL

func FailedRequestSummary

func FailedRequestSummary(resp *http.Response, err error) string

FailedRequestSummary returns a string that you can emit into a log message, when an HTTP request that you've made fails

func FailedRequestSummaryEx

func FailedRequestSummaryEx(resp *http.Response, err error, maxBodyLen int) string

FailedRequestSummaryEx returns a string that you can emit into a log message, when an HTTP request that you've made fails

func FetchJSON

func FetchJSON(req *http.Request, output any) error

func Handle

func Handle(log logs.Log, router *httprouter.Router, method, path string, handle httprouter.Handle)

Handle adds a protected HTTP route to router (ie handle will run inside RunProtected, so you get a panic handler).

func IsNotModified

func IsNotModified(w http.ResponseWriter, r *http.Request, modifiedAt time.Time) bool

func IsNotModifiedEx

func IsNotModifiedEx(w http.ResponseWriter, r *http.Request, modifiedAt time.Time, cacheControl string) bool

IsNotModified checks for an If-Modified-Since header, and if modifiedAt is before or equal to the header value, then we write a 304 Not Modified to w, and return true. If, on the other hand, modifiedAt is greater than If-Modified-Since (or the If-Modified-Since header is not present), then we set the Last-Modified header on w, and return false.

func Panic

func Panic(code int, message string)

Panic creates an HTTPError object and panics it.

func PanicBadRequest

func PanicBadRequest()

PanicBadRequest panics with a 400 Bad Request.

func PanicBadRequestf

func PanicBadRequestf(format string, args ...interface{})

PanicBadRequestf panics with a 400 Bad Request.

func PanicForbidden

func PanicForbidden()

PanicForbidden panics with a 403 Forbidden.

func PanicForbiddenf

func PanicForbiddenf(format string, args ...interface{})

func PanicNoContent

func PanicNoContent()

PanicNoContent panics with a 204 No Content.

func PanicNotFound

func PanicNotFound()

PanicNotFound panics with a 404 Not Found.

func PanicServerError

func PanicServerError(msg string)

PanicServerError panics with a 500 Internal Server Error

func PanicServerErrorf

func PanicServerErrorf(format string, args ...interface{})

PanicServerErrorf panics with a 500 Internal Server Error

func PanicUnauthorized

func PanicUnauthorized()

PanicForbidden panics with a 403 Forbidden.

func ParseID

func ParseID(s string) int64

ParseID parses a 64-bit integer, and returns zero on failure.

func QueryFloat64

func QueryFloat64(r *http.Request, key string) float64

Returns the named query value as a float64, or zero if the item is missing or not parseable as an integer

func QueryInt

func QueryInt(r *http.Request, key string) int

Returns the named query value as an int, or zero if the item is missing or not parseable as an integer

func QueryInt64

func QueryInt64(r *http.Request, key string) int64

Returns the named query value as an int64, or zero if the item is missing or not parseable as an integer

func QueryIntArray

func QueryIntArray[T constraints.Integer](r *http.Request, key string) []T

Returns the named query value as an array of integers, split by commas. Panics if the value is not parseable as an integer.

func QueryValue

func QueryValue(r *http.Request, key string) string

Returns the named query value (or an empty string)

func QueryValueEx

func QueryValueEx(r *http.Request, s string) (string, bool)

Returns (value, true) if a query value exists (an empty string counts as existence). Returns ("", false) if the query value does not exist

func RateLimit

func RateLimit(groupName string, maxPerSecond float64, w http.ResponseWriter, r *http.Request)

This is simple, dumb, and wrong, but at least the intention is clearer than having time.Sleep() all over the place The key things broken here are: 1. We don't pay attention to who's calling 2. We always sleep 3. It's trivial to get around this by firing off 10000 simultaneous requests

func ReadIDList

func ReadIDList(r *http.Request) []int64

Read a comma-separated list of integer IDs

func ReadJSON

func ReadJSON(w http.ResponseWriter, r *http.Request, obj interface{}, maxBodyBytes int64)

ReadJSON reads the body of the request, and unmarshals it into 'obj'.

func ReadLimited

func ReadLimited(w http.ResponseWriter, r *http.Request, maxBodyBytes int64) []byte

Read the request body, but limit the number of bytes that will be read, to ensure the server isn't loaded heavily by faulty or malicious requests

func ReadString

func ReadString(w http.ResponseWriter, r *http.Request, maxBodyBytes int64) string

ReadString reads the body of the request, and returns it as a string

func RequiredQueryInt

func RequiredQueryInt(r *http.Request, key string) int

Returns the named query value as an int, or panics if the item is empty, missing, or not parseable as an integer

func RequiredQueryInt64

func RequiredQueryInt64(r *http.Request, key string) int64

Returns the named query value as an int64, or panics if the item is empty, missing, or not parseable as an integer

func RequiredQueryValue

func RequiredQueryValue(r *http.Request, key string) string

Returns the named query value, or panics if the item is empty or missing

func RunProtected

func RunProtected(log logs.Log, w http.ResponseWriter, r *http.Request, handler func())

RunProtected runs 'func' inside a panic handler that recognizes our special errors, and sends the appropriate HTTP response if a panic does occur.

func SendError

func SendError(w http.ResponseWriter, message string, code int)

SendError is identical to the standard library http.Error(), except that we don't append a \n to the message body

func SendFile

func SendFile(w http.ResponseWriter, r *http.Request, filename, contentType string)

SendFile sends a file (as direct content, not download)

func SendFileDownload

func SendFileDownload(w http.ResponseWriter, filename, contentType string, content []byte)

SendFileDownload sends a file for download

func SendFmt

func SendFmt(w http.ResponseWriter, any interface{})

SendFmt serializes 'any' via fmt.Sprintf("%v"), and sends it as text/plain

func SendID

func SendID(w http.ResponseWriter, id int64)

SendID sends the ID as text/plain

func SendInt64

func SendInt64(w http.ResponseWriter, id int64)

SendInt64 sends the number as text/plain

func SendJSON

func SendJSON(w http.ResponseWriter, obj interface{})

SendJSON encodes 'obj' to JSON, and sends it as an HTTP application/json response.

func SendJSONBool

func SendJSONBool(w http.ResponseWriter, v bool)

SendJSONBool sends "true" or "false" as an application/json response

func SendJSONID

func SendJSONID(w http.ResponseWriter, id int64)

SendJSONID sends the ID as {"id":<value>}

func SendJSONOpt

func SendJSONOpt(w http.ResponseWriter, obj interface{}, pretty bool)

func SendJSONRaw

func SendJSONRaw(w http.ResponseWriter, raw any)

Accept string, []byte, and io.Reader

func SendOK

func SendOK(w http.ResponseWriter)

SendOK sends "OK" as a text/plain response.

func SendTempFile

func SendTempFile(w http.ResponseWriter, r *http.Request, filename, contentType string)

SendTempFile calls SendFile, and then deletes the file when finished

func SendText

func SendText(w http.ResponseWriter, text string)

SendText sends text as an HTTP text/plain response

func SplitIDList

func SplitIDList(idList string) []int64

Split a list of IDs such as "345,789" by comma, and return the list as int64s. Will panic on bad input.

func TryMultipleTimes

func TryMultipleTimes(maxAttempts int, action func() error) error

Try to execute a function multiple times, and return the first error (or nil upon success) We backoff exponentially with 1s, 2s, 4s, 8s, etc.

Types

type HTTPError

type HTTPError struct {
	Code    int
	Message string
}

HTTPError is an object that can be panic'ed, and the outer HTTP handler function. Will return the appropriate HTTP error message.

func BadRequest

func BadRequest() HTTPError

func BadRequestf

func BadRequestf(format string, args ...interface{}) HTTPError

func Error

func Error(code int, message string) HTTPError

func Forbidden

func Forbidden() HTTPError

func Forbiddenf

func Forbiddenf(format string, args ...interface{}) HTTPError

func NoContent

func NoContent() HTTPError

func NotFound

func NotFound() HTTPError

func ServerError

func ServerError(msg string) HTTPError

func ServerErrorf

func ServerErrorf(format string, args ...interface{}) HTTPError

func Unauthorized

func Unauthorized() HTTPError

func (HTTPError) Error

func (e HTTPError) Error() string

Jump to

Keyboard shortcuts

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