Skip to content

gofika/graceful

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Build Status go.dev Go Report Card Licenses donate

Graceful

Graceful helpers for golang

Basic Usage

Installation

To get the package, execute:

go get -u github.com/gofika/graceful

To import this package, add the following line to your code:

import "github.com/gofika/graceful";

Example

Here is example usage.

package main

import (
    "log"
    "net/http"

    "github.com/gofika/graceful"
)

func main() {
    ctx, _, gracefulClose := graceful.NewShutdown(context.Background())
    r := http.NewServeMux()
    r.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusOK)
        w.Header().Set("Content-Type", "application/text")
        w.Write([]byte("Success"))
    }))
    // Create a HTTP server and bind the router to it, and set wanted address
    srv := &http.Server{
        Handler: r,
        Addr:    ":8080",
    }
    // Append closer for graceful shutdown
    gracefulClose(func() { srv.Close() })
    // Run HTTP server. Server will graceful close util Ctrl+C signal
    if err := srv.ListenAndServe(); err != nil {
        if err != http.ErrServerClosed {
            log.Fatalf("server error: %s", err.Error())
        }
    }
}