github.com/l3x/learn-fp-go@v0.0.0-20171228022418-7639825d0b71/3-functional-techniques/ch07-func-param/01_func_param/main.go (about)

     1  package main
     2  
     3  import (
     4  	"server"
     5  	. "utils"
     6  	"context"
     7  	"io/ioutil"
     8  	"net/http"
     9  	"os"
    10  	"os/signal"
    11  	"time"
    12  	"fmt"
    13  )
    14  
    15  func init() {
    16  	GetOptions()
    17  	InitLog("trace-log.txt", ioutil.Discard, os.Stdout, os.Stderr)
    18  }
    19  
    20  func main() {
    21  	quit := make(chan os.Signal, 1)
    22  	signal.Notify(quit, os.Interrupt)
    23  	Info.Printf("Config %+v", Config)
    24  	newServer, err := server.New(
    25  		server.MaxConcurrentConnections(4),
    26  		server.MaxNumber(256), // Config.MaxNumber
    27  		server.UseNumberHandler(true),
    28  		server.FormatNumber(func(x int) (string, error) { return fmt.Sprintf("%x", x), nil }),  // anonymous fcn
    29  		//server.FormatNumber(func(x int) (string, error) { return fmt.Sprintf("%b", x), nil }),  // anonymous fcn
    30  		//server.FormatNumber(func(x int) (string, error) { return "", errors.New("FormatNumber error") }),  // anonymous fcn
    31  	)
    32  	if err != nil {
    33  		Error.Printf("unable to initialize server: %v", err)
    34  		os.Exit(1)
    35  	}
    36  	srv := &http.Server{
    37  		Addr:    ":"+ Config.Port,
    38  		Handler: newServer,
    39  	}
    40  
    41  	go func() {
    42  		<-quit
    43  		ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(2 * time.Second))
    44  		defer cancel()
    45  		Info.Println("shutting down server...")
    46  		if err := srv.Shutdown( ctx ); err != nil {
    47  			Error.Printf("unable to shutdown server: %v", err)
    48  		}
    49  	}()
    50  	Error.Println("server started at localhost:"+ Config.Port)
    51  	err = srv.ListenAndServe()
    52  	if err != nil && err != http.ErrServerClosed {
    53  		Error.Printf("ListenAndServe error: %v", err)
    54  	}
    55  	Info.Println("server shutdown gracefully")
    56  }