This repository has been archived on 2023-04-18. You can view files and clone it, but cannot push or open issues or pull requests.
notificationarr/main.go

63 lines
1.4 KiB
Go

package main
import (
"context"
"io"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
const (
defaultPort = "9234"
readTimeout = 2 * time.Second
readHeaderTimeout = 2 * time.Second
writeTimeout = 2 * time.Second
idleTimeout = 2 * time.Second
serverShutdownTimeout = 10 * time.Second
)
func main() {
srv := newServer()
go func(srv *http.Server) {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalln("srv.ListenAndServe:", err)
}
}(srv)
log.Println("Server is listening on the port", defaultPort)
waitForSignal(context.Background())
ctxShutdown, cancelShutdown := context.WithTimeout(context.Background(), serverShutdownTimeout)
defer cancelShutdown()
err := srv.Shutdown(ctxShutdown)
if err != nil {
log.Println("srv.Shutdown:", err)
}
}
func newServer() *http.Server {
return &http.Server{
Addr: ":" + defaultPort,
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.Copy(os.Stdout, r.Body)
w.WriteHeader(http.StatusOK)
}),
ReadTimeout: readTimeout,
ReadHeaderTimeout: readHeaderTimeout,
WriteTimeout: writeTimeout,
IdleTimeout: idleTimeout,
}
}
func waitForSignal(ctx context.Context) {
ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)
defer stop()
<-ctx.Done()
}