httpserver

package
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Aug 21, 2024 License: MIT Imports: 14 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultNotFoundHandler = func(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	if NotFound404Code {
		w.WriteHeader(http.StatusNotFound)
	} else {
		w.WriteHeader(http.StatusOK)
	}
	w.Write([]byte("{\"code\":404,\"error\":\"not found\"}\n"))
}

DefaultNotFoundHandler simple json error response

If NotFound404Code is true, will reply with a 404 status code otherwise, will reply with a 200 status code

View Source
var EscapeHTML = new(bool)

EscapeHTML is a global setting to escape html in json responses (ServeJson, ServeJsonIndent)

Default is false (no html escape)

If nil, uses the default json encoder settings (escapes < > etc)

To set true, use: `*http.EscapeHTML = true`

View Source
var IdleTimeout = time.Second * 2
View Source
var NotFound404Code = false

NotFound404Code is a global setting to reply with a 404 status code with the *default* not found handler Default is false (200 status code, 404/"not found" in json response)

View Source
var OneClosesBoth = true

OneClosesBoth is a global setting to close both of the http+https stack when one of them closes

View Source
var UUIDFunc = func(c net.Conn) int {
	return rand.Intn(1000) + 1000
}

UUIDFunc may be replaced (for example, ordered UUIDs)

Functions

func ServeJson added in v0.0.4

func ServeJson(w http.ResponseWriter, code int, v any)

func ServeJsonIndent added in v0.0.4

func ServeJsonIndent(w http.ResponseWriter, code int, v any)

func ShutdownServer

func ShutdownServer(server *http.Server, timeout time.Duration)

ShutdownServer with timeout

Types

type Config

type Config struct {
	BaseURL string `json:"base_url"`
}

Config is only for convenience, used by your application and middlewares

func (*Config) GetBaseURL

func (c *Config) GetBaseURL() string

type HttpServer

type HttpServer struct {
	*http.Server
	*superchan.Superchan[os.Signal]

	*http.ServeMux // at the bottom of all middleware

	*Config
	// contains filtered or unexported fields
}

HttpServer handles signals, use as main context

func New

func New(ctx context.Context, routes *http.ServeMux, signals ...os.Signal) *HttpServer

New creates an httpserver (http+https) that closes on cancellation or provided signals (SIGINT, SIGHUP etc) After New, set ErrorLog and routing (Handle, SetHomeHandler, SetNotFoundHandler), then run ListenAndServeAll. Caller MUST NOT Handle("/") as it is reserved for the home/notfound combo handler. Will panic if handler is a servemux that already handles "/" path.

See NewDefault for the typical setup.

func NewDefault

func NewDefault() *HttpServer

NewDefault creates a new httpserver using http.DefaultServeMux and sane default signals to handle (SIGHUP, SIGINT, SIGTERM)

Assigns ErrorLog to log.Default()

After NewDefault (probably as global var in main package), set ErrorLog and routing (Handle, HandleFunc, SetHomeHandler, SetNotFoundHandler), then run ListenAndServeAll followed by Wait() to make sure cleanup functions run properly.

func (*HttpServer) DeferFirst

func (h *HttpServer) DeferFirst(f func())

DeferFirst override because httpserver occupies superchan.DeferFirst

f will be called BEFORE http server shutdown begins

func (*HttpServer) DeferLast

func (h *HttpServer) DeferLast(f func())

DeferLast override because httpserver occupies superchan.DeferLast

f will be called AFTER all other deferred funcs, before ListenAndServeAll returns.

is persistent across server.Refresh() calls, but will be replaced if called again.

func (*HttpServer) InsertMiddleware

func (s *HttpServer) InsertMiddleware(middleware ...func(http.Handler) http.Handler)

InsertMiddleware into the http server (if calling SwapServeMux, this must be called after)

Ordering: handlers added later are called first.

func (*HttpServer) ListenAndServe

func (s *HttpServer) ListenAndServe() error

func (*HttpServer) ListenAndServeAll

func (s *HttpServer) ListenAndServeAll(httpAddr string, httpsAddr string, cert, key string) error

ListenAndServeAll starts the http server (http+https) and blocks until done. It will return an error if the server is cancelled or encounters an error during startup. After returning, Refresh() can be called before calling again

func (*HttpServer) ListenAndServeTLS

func (s *HttpServer) ListenAndServeTLS(string, string) error

func (*HttpServer) Refresh

func (s *HttpServer) Refresh(newmainctx context.Context) error

Refresh ONLY after closing the server (resets channel, context, reuses ServeMux) Will panic if called before server is closed. ONLY returns error if refreshfunc returns an error, in which case it cancels the context.

If using Refresh(), check error before adding superchan.Defer functions.

func (*HttpServer) RegisterOnShutdown

func (s *HttpServer) RegisterOnShutdown(f func())

RegisterOnShutdown registers a function to call on underlying http.Server.Shutdown.

also see the much more useful: Defer(func()) and DeferLast(func())

This can be used to gracefully shutdown connections that have undergone ALPN protocol upgrade or that have been hijacked. This function should start protocol-specific graceful shutdown, but should not wait for shutdown to complete.

func (*HttpServer) ServeJson

func (s *HttpServer) ServeJson(w http.ResponseWriter, code int, v any)

func (*HttpServer) ServeJsonIndent

func (s *HttpServer) ServeJsonIndent(w http.ResponseWriter, code int, v any)

func (*HttpServer) SetEntryMiddleware

func (s *HttpServer) SetEntryMiddleware(entrypoint func(http.Handler) http.Handler)

SetEntryMiddleware sets/replaces the (optional) top level middleware

Like InsertMiddleware but is inserted automatically at top level at "ListenAndServeAll" time

func (*HttpServer) SetHomeHandler

func (s *HttpServer) SetHomeHandler(h http.HandlerFunc)

func (*HttpServer) SetNotFoundHandler

func (s *HttpServer) SetNotFoundHandler(h http.HandlerFunc)

func (*HttpServer) SetRefreshFunc

func (h *HttpServer) SetRefreshFunc(f func(s *HttpServer) error)

called after Refresh() is completed, before Refresh() returns.

func (*HttpServer) SetShutdownFunc

func (h *HttpServer) SetShutdownFunc(f func())

SetShutdownFunc to run after http server is shutdown

func (*HttpServer) SwapServeMux

func (s *HttpServer) SwapServeMux(mux *http.ServeMux)

SwapServeMux with a new one (do this BEFORE calling InsertMiddleware) Will panic if already added middleware or "/" endpoint (eg. do not use http.DefaultServeMux with SwapServeMux)

Directories

Path Synopsis
httpctx package provides context keys for http server handlers.
httpctx package provides context keys for http server handlers.

Jump to

Keyboard shortcuts

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