いろいろ備忘録日記

主に .NET とか Go とか Flutter とか Python絡みのメモを公開しています。

Goメモ-226 (http.ListenAndServeで起動したサーバをシャットダウンする)

概要

よく忘れるので、以下にメモメモ。。。

そのまま http.ListenAndServe で起動すると当然駄目なので、http.Server を作って起動します。

サンプル

main.go

package main

import (
    "context"
    "log"
    "net/http"
    "time"
)

func main() {
    var (
        mux              = http.NewServeMux()
        srv              = &http.Server{Addr: ":8888", Handler: mux}
        mainCtx          = context.Background()
        procCtx, procCxl = context.WithTimeout(mainCtx, 3*time.Second)
    )
    defer procCxl()

    // ----------- Start ----------- //

    go func() {
        log.Println("Server is up.")
        srv.ListenAndServe()
    }()

    <-procCtx.Done()

    // ----------- Shutdown ----------- //

    var (
        shutdownCtx, shutdownCxl = context.WithTimeout(mainCtx, 1*time.Second)
    )
    defer shutdownCxl()

    if err := srv.Shutdown(shutdownCtx); err != nil {
        switch err {
        case context.DeadlineExceeded:
            log.Println("Server shutdown process timed out.")
        default:
            log.Fatal(err)
        }
    }
    log.Println("Server has been shutdown.")
}

Taskfile.yml

version: '3'

tasks:
  run:
    cmds:
      - go run -race main.go

実行すると以下のようになります。

gitpod /workspace/try-golang (master) $ task -d examples/http/shutdown/ run
task: [run] go run -race main.go
2022/07/23 08:41:30 Server is up.
2022/07/23 08:41:33 Server has been shutdown.

参考情報

stackoverflow.com


過去の記事については、以下のページからご参照下さい。

サンプルコードは、以下の場所で公開しています。