Documentation ¶
Overview ¶
Example ¶
package main import ( "fmt" "net/http" ) const ( port = 8080 ) func main() { // Create a new scaffold that will listen for HTTP on port 8080 scaf := CreateHTTPScaffold() scaf.SetInsecurePort(port) // Direct the scaffold to catch common signals and trigger a // graceful shutdown. scaf.CatchSignals() // Set up a URL that may be used by a load balancer to test // if the server is ready to handle requests scaf.SetReadyPath("/ready") // Set up a URL that may be used by infrastructure to test // if the server is working or if it needs to be restarted or replaced scaf.SetHealthPath("/healthy") listener := &TestListener{} fmt.Printf("Listening on %d\n", port) // Listen now. The listener will return when the server is actually // shut down. err := scaf.Listen(listener) // If we get here, and if we care to know, then the error will tell // us why we were shut down. fmt.Printf("HTTP server shut down: %s\n", err.Error()) } /* TestListener is an HTTP listener used for the example code. It just returns 200 and "Hello, World!" */ type TestListener struct { } func (l *TestListener) ServeHTTP(resp http.ResponseWriter, req *http.Request) { resp.Header().Set("Content-Type", "text/plain") resp.WriteHeader(http.StatusOK) resp.Write([]byte("Hello, World!")) }
Output:
Index ¶
- Constants
- Variables
- func FetchParams(r *http.Request) httprouter.Params
- func SelectMediaType(req *http.Request, choices []string) string
- func SetParamsInRequest(r *http.Request, ps httprouter.Params) *http.Request
- func WriteErrorResponse(statusCode int, message string, w http.ResponseWriter)
- type ErrorResponse
- type Errors
- type HTTPScaffold
- func (s *HTTPScaffold) CatchSignals()
- func (s *HTTPScaffold) CatchSignalsTo(out io.Writer)
- func (s *HTTPScaffold) CreateOAuth(keyURL string) OAuthService
- func (s *HTTPScaffold) InsecureAddress() string
- func (s *HTTPScaffold) Listen(baseHandler http.Handler) error
- func (s *HTTPScaffold) ManagementAddress() string
- func (s *HTTPScaffold) Open() error
- func (s *HTTPScaffold) SecureAddress() string
- func (s *HTTPScaffold) SetCertFile(fn string)
- func (s *HTTPScaffold) SetHealthChecker(c HealthChecker)
- func (s *HTTPScaffold) SetHealthPath(p string)
- func (s *HTTPScaffold) SetInsecurePort(port int)
- func (s *HTTPScaffold) SetKeyFile(fn string)
- func (s *HTTPScaffold) SetManagementPort(p int)
- func (s *HTTPScaffold) SetMarkdown(method, path string, handler MarkdownHandler)
- func (s *HTTPScaffold) SetReadyPath(p string)
- func (s *HTTPScaffold) SetSecurePort(port int)
- func (s *HTTPScaffold) SetlocalBindIPAddressV4(ip net.IP)
- func (s *HTTPScaffold) Shutdown(reason error)
- func (s *HTTPScaffold) StartListen(baseHandler http.Handler) error
- func (s *HTTPScaffold) WaitForShutdown() error
- type HealthChecker
- type HealthStatus
- type MarkdownHandler
- type OAuthService
Examples ¶
Constants ¶
const ( // DefaultGraceTimeout is the default amount of time to wait for a request // to complete. Default is 30 seconds, which is also the default grace period // in Kubernetes. DefaultGraceTimeout = 30 * time.Second )
Variables ¶
var ErrManualStop = errors.New("Shutdown called")
ErrManualStop is used when the user doesn't have a reason.
var ErrMarkedDown = errors.New("Marked down")
ErrMarkedDown is used after being marked down but before being shut down.
var ErrSignalCaught = errors.New("Caught shutdown signal")
ErrSignalCaught is used in the "Shutdown" mechanism when the shutdown was caused by a SIGINT or SIGTERM.
Functions ¶
func FetchParams ¶
func FetchParams(r *http.Request) httprouter.Params
FetchParams fetches the param values, given the params in the request
func SelectMediaType ¶
SelectMediaType matches a set of candidate media types against the Accept header in an HTTP request. It does this using the rules from RFC2616 section 1.4. If no Accept header is present, then the first choice in the "choices" array is returned. If multiple choices match, then we will take the first one specified in the "Accept" header. If there are no compatible media types, then an empty string is returned. Only the first "Accept" header on the request is considered.
func SetParamsInRequest ¶
SetParamsInRequest Sets the params and its values in the request
func WriteErrorResponse ¶
func WriteErrorResponse(statusCode int, message string, w http.ResponseWriter)
WriteErrorResponse write a non 200 error response
Types ¶
type ErrorResponse ¶
type ErrorResponse struct { Status string `json:"status"` Message string `json:"message"` Errors []string `json:"errors"` }
ErrorResponse delivers the errors back to the caller, once validation has failed
type HTTPScaffold ¶
type HTTPScaffold struct {
// contains filtered or unexported fields
}
An HTTPScaffold provides a set of features on top of a standard HTTP listener. It includes an HTTP handler that may be plugged in to any standard Go HTTP server. It is intended to be placed before any other handlers.
func CreateHTTPScaffold ¶
func CreateHTTPScaffold() *HTTPScaffold
CreateHTTPScaffold makes a new scaffold. The default scaffold will do nothing.
func (*HTTPScaffold) CatchSignals ¶
func (s *HTTPScaffold) CatchSignals()
CatchSignals directs the scaffold to listen for common signals. It catches three signals. SIGINT (aka control-C) and SIGTERM (what "kill" sends by default) will cause the program to be marked down, and "SignalCaught" will be returned by the "Listen" method. SIGHUP ("kill -1" or "kill -HUP") will cause the stack trace of all the threads to be printed to stderr, just like a Java program. This method is very simplistic -- it starts listening every time that you call it. So a program should only call it once.
func (*HTTPScaffold) CatchSignalsTo ¶
func (s *HTTPScaffold) CatchSignalsTo(out io.Writer)
CatchSignalsTo is just like CatchSignals, but it captures the stack trace to the specified writer rather than to os.Stderr. This is handy for testing.
func (*HTTPScaffold) CreateOAuth ¶
func (s *HTTPScaffold) CreateOAuth(keyURL string) OAuthService
CreateOAuth is a constructor that creates OAuth for OAuthService interface. OAuthService interface offers method:- (1) SSOHandler(): Offers the user to attach http handler for JWT verification.
func (*HTTPScaffold) InsecureAddress ¶
func (s *HTTPScaffold) InsecureAddress() string
InsecureAddress returns the actual address (including the port if an ephemeral port was used) where we are listening. It must only be called after "Listen."
func (*HTTPScaffold) Listen ¶
func (s *HTTPScaffold) Listen(baseHandler http.Handler) error
Listen is a convenience function that first calls "StartListen" and then calls "WaitForShutdown."
func (*HTTPScaffold) ManagementAddress ¶
func (s *HTTPScaffold) ManagementAddress() string
ManagementAddress returns the actual address (including the port if an ephemeral port was used) where we are listening for management operations. If "SetManagementPort" was not set, then it returns null.
func (*HTTPScaffold) Open ¶
func (s *HTTPScaffold) Open() error
Open opens up the ports that were created when the scaffold was set up. This method is optional. It may be called before Listen so that we can retrieve the actual address where the server is listening before we actually start to listen.
func (*HTTPScaffold) SecureAddress ¶
func (s *HTTPScaffold) SecureAddress() string
SecureAddress returns the actual address (including the port if an ephemeral port was used) where we are listening on HTTPS. It must only be called after "Listen."
func (*HTTPScaffold) SetCertFile ¶
func (s *HTTPScaffold) SetCertFile(fn string)
SetCertFile sets the name of the file that the server will read to get its own TLS certificate. It is only consulted if "securePort" is >= 0.
func (*HTTPScaffold) SetHealthChecker ¶
func (s *HTTPScaffold) SetHealthChecker(c HealthChecker)
SetHealthChecker specifies a function that the scaffold will call every time "HealthPath" or "ReadyPath" is invoked.
func (*HTTPScaffold) SetHealthPath ¶
func (s *HTTPScaffold) SetHealthPath(p string)
SetHealthPath sets up a health check on the management port (if set) or otherwise the main port. If a health check function has been supplied, it will return 503 if the function returns "Failed" and 200 otherwise. This path is intended to be used by systems like Kubernetes as the "health check." These systems will shut down the server if we return a non-200 URL.
func (*HTTPScaffold) SetInsecurePort ¶
func (s *HTTPScaffold) SetInsecurePort(port int)
SetInsecurePort sets the port number to listen on in regular "HTTP" mode. It may be set to zero, which indicates to listen on an ephemeral port. It must be called before "listen".
func (*HTTPScaffold) SetKeyFile ¶
func (s *HTTPScaffold) SetKeyFile(fn string)
SetKeyFile sets the name of the file that the server will read to get its own TLS key. It is only consulted if "securePort" is >= 0. If "getPass" is non-null, then the function will be called at startup time to retrieve the password for the key file.
func (*HTTPScaffold) SetManagementPort ¶
func (s *HTTPScaffold) SetManagementPort(p int)
SetManagementPort sets the port number for management operations, including health checks and diagnostic operations. If not set, then these operations happen on the other ports. If set, then they only happen on this port.
func (*HTTPScaffold) SetMarkdown ¶
func (s *HTTPScaffold) SetMarkdown(method, path string, handler MarkdownHandler)
SetMarkdown sets up a URI that will cause the server to mark it self down. However, this URI will not cause the server to actually shut down. Once any HTTP request is received on this path with a matching method, the server will be marked down. (the "readyPath" will respond with 503, and all other HTTP calls other than the "healthPath" will also respond with 503. The "healthPath" will still respond with 200.) If "handler" is not nil, the handler will be invoked and the API call will not return until the handler has returned. Because of that, the handler should return in a timely manner. (For instance, it should return in less than 30 seconds if Kubernetes is used unless the "grace period" is extended.) This makes this function the right thing to use as a "preStop" method in Kubernetes, so that the server can take action after shutdown to indicate that it has been deleted on purpose.
func (*HTTPScaffold) SetReadyPath ¶
func (s *HTTPScaffold) SetReadyPath(p string)
SetReadyPath sets up a readines check on the management port (if set) or otherwise the main port. If a health check function has been supplied, it will return 503 if the function returns "Failed" or "Not Ready". It will also return 503 if the "Shutdown" function was called (or caught by signal handler). This path is intended to be used by load balancers that will decide whether to route calls, but not by systems like Kubernetes that will decide to shut down this server.
func (*HTTPScaffold) SetSecurePort ¶
func (s *HTTPScaffold) SetSecurePort(port int)
SetSecurePort sets the port number to listen on in HTTPS mode. It may be set to zero, which indicates to listen on an ephemeral port. It must be called before Listen. It is an error to call Listen if this port is set and if the key and secret files are not also set.
func (*HTTPScaffold) SetlocalBindIPAddressV4 ¶
func (s *HTTPScaffold) SetlocalBindIPAddressV4(ip net.IP)
SetlocalBindIPAddressV4 seta the IP address (IP V4) for the service to bind on to listen on. If none set, all IP addesses would be accepted.
func (*HTTPScaffold) Shutdown ¶
func (s *HTTPScaffold) Shutdown(reason error)
Shutdown indicates that the server should stop handling incoming requests and exit from the "Serve" call. This may be called automatically by calling "CatchSignals," or automatically using this call. If "reason" is nil, a default reason will be assigned.
func (*HTTPScaffold) StartListen ¶
func (s *HTTPScaffold) StartListen(baseHandler http.Handler) error
StartListen should be called instead of using the standard "http" and "net" libraries. It will open a port (or ports) and begin listening for HTTP traffic.
func (*HTTPScaffold) WaitForShutdown ¶
func (s *HTTPScaffold) WaitForShutdown() error
WaitForShutdown blocks until we are shut down. It will use the graceful shutdown logic to ensure that once marked down, the server will not exit until all the requests have completed, or until the shutdown timeout has expired. Like http.Serve, this function will block until we are done serving HTTP. If "SetInsecurePort" or "SetSecurePort" were not set, then it will listen on a dynamic port. This method will block until the server is shutdown using "Shutdown" or one of the other shutdown mechanisms. It must not be called until after "StartListenen" When shut down, this method will return the error that was passed to the "shutdown" method.
type HealthChecker ¶
type HealthChecker func() (HealthStatus, error)
HealthChecker is a type of function that an implementer may implement in order to customize what we return from the "health" and "ready" URLs. It must return either "OK", which means that everything is fine, "not ready," which means that the "ready" check will fail but the health check is OK, and "failed," which means that both are bad. The function may return an optional error, which will be returned as a reason for the status and will be placed in responses.
type HealthStatus ¶
type HealthStatus int
HealthStatus is a type of response from a health check.
const ( // OK denotes that everything is good OK HealthStatus = iota // NotReady denotes that the server is OK, but cannot process requests now NotReady HealthStatus = iota // Failed denotes that the server is bad Failed HealthStatus = iota )
func (HealthStatus) String ¶
func (i HealthStatus) String() string
type MarkdownHandler ¶
type MarkdownHandler func()
MarkdownHandler is a type of function that an user may implement in order to be notified when the server is marked down. The function may do anything it needs to do in response to a markdown request. However, markdown will proceed even if the function fails. In case the function takes a long time, the scaffold will always invoke it inside a new goroutine.
type OAuthService ¶
type OAuthService interface {
SSOHandler(p string, h func(http.ResponseWriter, *http.Request)) (string, httprouter.Handle)
}
OAuthService offers interface functions that act on OAuth param, used to verify JWT tokens for the Http handler functions client wishes to validate against (via SSOHandler).