Created
June 7, 2022 13:47
-
-
Save eminetto/fa5c447b1e4a7a5e544463562ad37782 to your computer and use it in GitHub Desktop.
Exemplo de graceful 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" | |
"fmt" | |
"log" | |
"net/http" | |
"os" | |
"os/signal" | |
"syscall" | |
"time" | |
) | |
func main() { | |
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) | |
defer cancel() | |
go func() { | |
c := make(chan os.Signal, 1) // we need to reserve to buffer size 1, so the notifier are not blocked | |
signal.Notify(c, os.Interrupt, syscall.SIGTERM) | |
<-c | |
log.Println("recebido control+c") | |
cancel() | |
}() | |
//lembre-se sempre de configurar os timeouts do servidor | |
httpServer := &http.Server{ | |
ReadTimeout: 30 * time.Second, | |
WriteTimeout: 30 * time.Second, | |
Addr: ":8000", | |
} | |
//exemplo de uma aplicação que tem um worker rodando além da api. Por exemplo, para responder a eventos de uma fila | |
go func() { | |
worker(ctx) | |
}() | |
//para o servidor quando recebe o sinal | |
go func() { | |
<-ctx.Done() | |
log.Println("parando servidor web") | |
err := httpServer.Shutdown(context.Background()) | |
if err != nil { | |
panic(err) | |
} | |
}() | |
http.HandleFunc("/", hello) | |
log.Println("iniciando servidor web") | |
err := httpServer.ListenAndServe() | |
if err != nil { | |
log.Printf("exit reason: %s \n", err) | |
} | |
} | |
func hello(w http.ResponseWriter, r *http.Request) { | |
w.Write([]byte("Hello, HTTP!\n")) | |
} | |
func worker(ctx context.Context) { | |
for { | |
select { | |
case <-ctx.Done(): | |
fmt.Println("Graceful worker exit") | |
return | |
case <-time.After(1 * time.Second): | |
fmt.Println("Hello in a loop") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment