Created
June 19, 2024 18:10
-
-
Save macedo/3798409229c8694d28d33db386410ee2 to your computer and use it in GitHub Desktop.
server gracefull shutdown
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"errors" | |
"log" | |
"net/http" | |
"os" | |
"os/signal" | |
"syscall" | |
"time" | |
) | |
func main() { | |
server := &http.Server{ | |
Addr: ":8080", | |
} | |
http.Handle("/", http.FileServer(http.Dir("./public"))) | |
go func() { | |
if err := server.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) { | |
log.Fatalf("HTTP server error: %v", err) | |
} | |
log.Println("Stopped serving new connections.") | |
}() | |
sigChan := make(chan os.Signal, 1) | |
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM) | |
<-sigChan | |
shutdownCtx, shutdownRelease := context.WithTimeout(context.Background(), 10*time.Second) | |
defer shutdownRelease() | |
if err := server.Shutdown(shutdownCtx); err != nil { | |
log.Fatalf("HTTP shutdown error: %v", err) | |
} | |
log.Println("Graceful shutdown complete.") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment