Skip to content

Commit

Permalink
Merge pull request #13 from franciscovalentecastro/fcovalente-handle-…
Browse files Browse the repository at this point in the history
…sigterm

main: Handle SIGTERM and gracefully shutdown.
  • Loading branch information
franciscovalentecastro authored Nov 21, 2023
2 parents 22261a9 + 5a8f2c8 commit 353a859
Showing 1 changed file with 29 additions and 2 deletions.
31 changes: 29 additions & 2 deletions app/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import (
"log"
"net/http"
"os"
"os/signal"
"syscall"

"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc"
Expand All @@ -32,6 +34,8 @@ import (
"go.opentelemetry.io/otel/trace"
)

// Create channel to listen for signals.
var signalChan chan (os.Signal) = make(chan os.Signal, 1)
var counter instrument.Int64Counter

func main() {
Expand Down Expand Up @@ -70,8 +74,31 @@ func main() {
log.Fatalf("Error creating counter: %s", err)
}

http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe(":8080", nil))
// SIGINT handles Ctrl+C locally.
// SIGTERM handles Cloud Run termination signal.
signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)

// Start HTTP server.
srv := &http.Server{
Addr: ":8080",
Handler: http.HandlerFunc(handler),
}
go func() {
http.HandleFunc("/", handler)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatal(err)
}
}()

// Receive output from signalChan.
sig := <-signalChan
log.Printf("%s signal caught. Graceful Shutdown.", sig)

// Gracefully shutdown the server by waiting on existing requests (except websockets).
if err := srv.Shutdown(ctx); err != nil {
log.Printf("server shutdown failed: %+v", err)
}
log.Print("server exited")
}

func traceLogPrefix(traceId, spanId string) string {
Expand Down

0 comments on commit 353a859

Please sign in to comment.