59 lines
1.2 KiB
Go
59 lines
1.2 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"syscall"
|
|
"time"
|
|
)
|
|
|
|
const defaultPort = "8080"
|
|
|
|
func port() string {
|
|
if p := os.Getenv("PORT"); p != "" {
|
|
return p
|
|
}
|
|
return defaultPort
|
|
}
|
|
|
|
func newHandler() http.Handler {
|
|
mux := http.NewServeMux()
|
|
mux.HandleFunc("GET /health", healthOK)
|
|
mux.HandleFunc("GET /healthz", healthOK)
|
|
mux.HandleFunc("GET /{$}", productPage)
|
|
return mux
|
|
}
|
|
|
|
func healthOK(w http.ResponseWriter, _ *http.Request) {
|
|
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
|
_, _ = w.Write([]byte("ok"))
|
|
}
|
|
|
|
func main() {
|
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
|
defer stop()
|
|
|
|
srv := &http.Server{Addr: ":" + port(), Handler: newHandler(), ReadHeaderTimeout: 5 * time.Second}
|
|
|
|
errCh := make(chan error, 1)
|
|
go func() { errCh <- srv.ListenAndServe() }()
|
|
log.Printf("listening on %s", srv.Addr)
|
|
|
|
select {
|
|
case err := <-errCh:
|
|
log.Fatal(err)
|
|
case <-ctx.Done():
|
|
}
|
|
|
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
if err := srv.Shutdown(shutdownCtx); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
|
log.Fatal(err)
|
|
}
|
|
log.Print("stopped")
|
|
}
|