Skip to content

Instantly share code, notes, and snippets.

@singhsays
Created March 13, 2023 06:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save singhsays/2bfaef88d1952971cabaedc10a1278a1 to your computer and use it in GitHub Desktop.
Save singhsays/2bfaef88d1952971cabaedc10a1278a1 to your computer and use it in GitHub Desktop.
Basic golang http server with graceful shutdown
package main
import (
"context"
"flag"
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/golang/glog"
"github.com/pkg/errors"
)
var (
// http server flags
httpAddress = flag.String("http_address", "", "host or ip address for the http server.")
httpPort = flag.Int("http_port", 8080, "port for the http server.")
httpShutdownTimeout = flag.Duration("http_shutdown_duration", 5*time.Second, "duration to allow for graceful http server shutdown.")
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "OK")
}
func main() {
// Parse flags
flag.Parse()
http.HandleFunc("/", handler)
addr := fmt.Sprintf("%s:%d", *httpAddress, *httpPort)
srv := &http.Server{Addr: addr}
// Create a channel to receive OS signals
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
// Start the server in a goroutine
go func() {
glog.Infof("Listening on %s", addr)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
glog.Errorf("Error starting server: %v\n", err)
os.Exit(1)
}
}()
// Block until a signal is received
sig := <-sigChan
glog.Infof("Received signal %s\n", sig)
// Create a context to gracefully shutdown the server
ctx, cancel := context.WithTimeout(context.Background(), *httpShutdownTimeout)
defer cancel()
// Attempt to shutdown the server
if err := srv.Shutdown(ctx); err != nil {
glog.Errorf("Error shutting down server: %v\n", err)
}
glog.Info("Server gracefully stopped")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment