package server
import "gocloud.dev/server"
Package server provides a preconfigured HTTP server with diagnostic hooks.
Index ¶
- Variables
- type DefaultDriver
- func NewDefaultDriver() *DefaultDriver
- func (dd *DefaultDriver) ListenAndServe(addr string, h http.Handler) error
- func (dd *DefaultDriver) ListenAndServeTLS(addr, certFile, keyFile string, h http.Handler) error
- func (dd *DefaultDriver) Shutdown(ctx context.Context) error
- type Options
- type Server
Examples ¶
Variables ¶
var Set = wire.NewSet( New, wire.Struct(new(Options), "RequestLogger", "HealthChecks", "TraceExporter", "DefaultSamplingPolicy", "Driver"), wire.Value(&DefaultDriver{}), wire.Bind(new(driver.Server), new(*DefaultDriver)), )
Set is a Wire provider set that produces a *Server given the fields of Options.
Types ¶
type DefaultDriver ¶
DefaultDriver implements the driver.Server interface. The zero value is a valid http.Server.
func NewDefaultDriver ¶
func NewDefaultDriver() *DefaultDriver
NewDefaultDriver creates a driver with an http.Server with default timeouts.
func (*DefaultDriver) ListenAndServe ¶
func (dd *DefaultDriver) ListenAndServe(addr string, h http.Handler) error
ListenAndServe sets the address and handler on DefaultDriver's http.Server, then calls ListenAndServe on it.
func (*DefaultDriver) ListenAndServeTLS ¶
func (dd *DefaultDriver) ListenAndServeTLS(addr, certFile, keyFile string, h http.Handler) error
ListenAndServeTLS sets the address and handler on DefaultDriver's http.Server, then calls ListenAndServeTLS on it.
DefaultDriver.Server.TLSConfig may be set to configure additional TLS settings.
func (*DefaultDriver) Shutdown ¶
func (dd *DefaultDriver) Shutdown(ctx context.Context) error
Shutdown gracefully shuts down the server without interrupting any active connections, by calling Shutdown on DefaultDriver's http.Server
type Options ¶
type Options struct { // RequestLogger specifies the logger that will be used to log requests. RequestLogger requestlog.Logger // HealthChecks specifies the health checks to be run when the // /healthz/readiness endpoint is requested. HealthChecks []health.Checker // TraceExporter exports sampled trace spans. TraceExporter trace.Exporter // DefaultSamplingPolicy is a function that takes a // trace.SamplingParameters struct and returns a true or false decision about // whether it should be sampled and exported. DefaultSamplingPolicy trace.Sampler // Driver serves HTTP requests. Driver driver.Server }
Options is the set of optional parameters.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is a preconfigured HTTP server with diagnostic hooks.
The zero value is a server with the default options.
Code:play
Code:play
Code:play
Example¶
package main
import (
"fmt"
"log"
"net/http"
"gocloud.dev/server"
)
func main() {
// PRAGMA: This example is used on gocloud.dev; PRAGMA comments adjust how it is shown and can be ignored.
// Use the constructor function to create the server.
srv := server.New(http.DefaultServeMux, nil)
// Register a route.
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello, World!")
})
// Start the server. If ListenAndServe returns an error, print it and exit.
if err := srv.ListenAndServe(":8080"); err != nil {
log.Fatalf("%v", err)
}
}
Example (WithHealthChecks)¶
package main
import (
"errors"
"fmt"
"log"
"net/http"
"sync"
"time"
"gocloud.dev/server"
"gocloud.dev/server/health"
)
// customHealthCheck is an example health check. It implements the
// health.Checker interface and reports the server is healthy when the healthy
// field is set to true.
type customHealthCheck struct {
mu sync.RWMutex
healthy bool
}
// customHealthCheck implements the health.Checker interface because it has a
// CheckHealth method. Because each application may have a different definition
// of what it means to be "healthy", you will need to define a CheckHealth method
// specific to your application.
func (h *customHealthCheck) CheckHealth() error {
h.mu.RLock()
defer h.mu.RUnlock()
if !h.healthy {
return errors.New("not ready yet!")
}
return nil
}
func main() {
// PRAGMA: This example is used on gocloud.dev; PRAGMA comments adjust how it is shown and can be ignored.
// Create a health.Checker from the type we defined for our application.
// In this example, healthCheck will report the server is unhealthy for 10 seconds
// after startup, and as healthy henceforth. Check the /healthz/readiness
// HTTP path to see readiness.
healthCheck := new(customHealthCheck)
time.AfterFunc(10*time.Second, func() {
healthCheck.mu.Lock()
defer healthCheck.mu.Unlock()
healthCheck.healthy = true
})
// The server.Options struct takes a slice of health checks, because you
// may need to check several things.
srvOptions := &server.Options{
HealthChecks: []health.Checker{healthCheck},
}
// Pass the options to the Server constructor.
srv := server.New(http.DefaultServeMux, srvOptions)
// Register a route.
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello, World!")
})
// Start the server. You will see requests logged to STDOUT.
if err := srv.ListenAndServe(":8080"); err != nil {
log.Fatalf("%v", err)
}
}
Example (WithRequestLogger)¶
package main
import (
"fmt"
"log"
"net/http"
"os"
"gocloud.dev/server"
"gocloud.dev/server/requestlog"
)
func main() {
// PRAGMA: This example is used on gocloud.dev; PRAGMA comments adjust how it is shown and can be ignored.
// Create a logger, and assign it to the RequestLogger field of a
// server.Options struct.
srvOptions := &server.Options{
RequestLogger: requestlog.NewNCSALogger(os.Stdout, func(error) {}),
}
// Pass the options to the Server constructor.
srv := server.New(http.DefaultServeMux, srvOptions)
// Register a route.
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello, World!")
})
// Start the server. You will see requests logged to STDOUT.
if err := srv.ListenAndServe(":8080"); err != nil {
log.Fatalf("%v", err)
}
}
func New ¶
New creates a new server. New(nil, nil) is the same as new(Server).
func (*Server) ListenAndServe ¶
ListenAndServe is a wrapper to use wherever http.ListenAndServe is used. It wraps the http.Handler provided to New with a handler that handles tracing and request logging. If the handler is nil, then http.DefaultServeMux will be used. A configured Requestlogger will log all requests except HealthChecks.
func (*Server) ListenAndServeTLS ¶
ListenAndServeTLS is a wrapper to use wherever http.ListenAndServeTLS is used. It wraps the http.Handler provided to New with a handler that handles tracing and request logging. If the handler is nil, then http.DefaultServeMux will be used. A configured Requestlogger will log all requests except HealthChecks.
func (*Server) Shutdown ¶
Shutdown gracefully shuts down the server without interrupting any active connections.
Code:play
Example¶
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"gocloud.dev/server"
)
func main() {
// OPTIONAL: Specify a driver in the options for the constructor.
// NewDefaultDriver will be used by default if it is not explicitly set, and
// uses http.Server with read, write, and idle timeouts set. When Shutdown
// is called on the server, it is called on the driver.
srvOptions := &server.Options{
Driver: server.NewDefaultDriver(),
}
// Pass the options to the Server constructor.
srv := server.New(http.DefaultServeMux, srvOptions)
// If your application will be behind a load balancer that handles graceful
// shutdown of requests, you may not need to call Shutdown on the server
// directly. If you need to ensure graceful shutdown directly, it is important
// to have a separate goroutine, because ListenAndServe blocks indefinitely.
go func() {
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
// Receive off the chanel in a loop, because the interrupt could be sent
// before ListenAndServe starts.
for {
<-interrupt
srv.Shutdown(context.Background())
}
}()
// Register a route.
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello, World!")
})
// Start the server. You will see requests logged to STDOUT.
// In the absence of an error, ListenAndServe blocks forever.
if err := srv.ListenAndServe(":8080"); err != nil {
log.Fatalf("%v", err)
}
}
Source Files ¶
server.go
Directories ¶
Path | Synopsis |
---|---|
server/driver | Package driver defines an interface for custom HTTP listeners. |
server/health | Package health provides health check handlers. |
server/health/sqlhealth | Package sqlhealth provides a health check for a SQL database connection. |
server/requestlog | Package requestlog provides an http.Handler that logs information about requests. |
server/sdserver | Package sdserver provides the diagnostic hooks for a server using Stackdriver. |
server/xrayserver | Package xrayserver provides the diagnostic hooks for a server using AWS X-Ray. |
- Version
- v0.41.0
- Published
- Mar 30, 2025
- Platform
- js/wasm
- Imports
- 11 packages
- Last checked
- 2 hours ago –
Tools for package owners.