“Contoh Golang Shutdown anggun” Kode Jawaban

Contoh Golang Shutdown anggun

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

Contoh Golang Shutdown anggun

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

Jawaban yang mirip dengan “Contoh Golang Shutdown anggun”

Pertanyaan yang mirip dengan “Contoh Golang Shutdown anggun”

Lebih banyak jawaban terkait untuk “Contoh Golang Shutdown anggun” di Go

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya