“Golang Exemple de fermeture gracieuse” Réponses codées

Golang Exemple de fermeture gracieuse

package main

import (
	"context"
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"time"
)

const (
	service = "fooapi"
)

var (
	port            = flag.Int("port", 3333, "http port to listen on")
	shutdownTimeout = flag.Duration("shutdown-timeout", 10*time.Second,
		"shutdown timeout (5s,5m,5h) before connections are cancelled")
)

func main() {
	flag.Parse()

	mux := http.NewServeMux()
	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(200)
	})

	srv := &http.Server{
		Addr:    fmt.Sprintf(":%d", *port),
		Handler: mux,
	}

	stop := make(chan os.Signal)
	signal.Notify(stop, os.Interrupt)

	go func() {
		log.Printf("%s listening on 0.0.0.0:%d with %v timeout", service, *port, *shutdownTimeout)
		if err := srv.ListenAndServe(); err != nil {
			if err != http.ErrServerClosed {
				log.Fatal(err)
			}
		}
	}()

	<-stop

	log.Printf("%s shutting down ...\n", service)

	ctx, cancel := context.WithTimeout(context.Background(), *shutdownTimeout)
	defer cancel()

	if err := srv.Shutdown(ctx); err != nil {
		log.Fatal(err)
	}

	log.Printf("%s down\n", service)
}
Restu Wahyu Saputra

Golang Exemple de fermeture gracieuse

package main

import (
    "context"
    "errors"
    "log"
    "net/http"
    "os"
    "os/signal"
    "syscall"
    "time"
)

func createChannel() (chan os.Signal, func()) {
    stopCh := make(chan os.Signal, 1)
    signal.Notify(stopCh, os.Interrupt, syscall.SIGTERM, syscall.SIGINT)

    return stopCh, func() {
        close(stopCh)
    }
}

func start(server *http.Server) {
    log.Println("application started")
    if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
        panic(err)
    } else {
        log.Println("application stopped gracefully")
    }
}

func shutdown(ctx context.Context, server *http.Server) {
    ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
    defer cancel()

    if err := server.Shutdown(ctx); err != nil {
        panic(err)
    } else {
        log.Println("application shutdowned")
    }
}

func main() {
    log.SetFlags(log.Lshortfile)
    s := &http.Server{}
    go start(s)

    stopCh, closeCh := createChannel()
    defer closeCh()
    log.Println("notified:", <-stopCh)

    shutdown(context.Background(), s)
}
Restu Wahyu Saputra

Réponses similaires à “Golang Exemple de fermeture gracieuse”

Questions similaires à “Golang Exemple de fermeture gracieuse”

Plus de réponses similaires à “Golang Exemple de fermeture gracieuse” dans Go

Parcourir les réponses de code populaires par langue

Parcourir d'autres langages de code