其他分享
首页 > 其他分享> > Gin实践 连载六 Golang优雅重启HTTP服务

Gin实践 连载六 Golang优雅重启HTTP服务

作者:互联网

http.Server-Shutdown()

package main

import (
	"context"
	"fmt"
	_ "gin_log/models"
	"gin_log/pkg/setting"
	"gin_log/routers"
	"log"
	"net/http"
	"os"
	"os/signal"
	"time"
)

func main() {
	router := routers.InitRouter()
	s := &http.Server{
		Addr:           fmt.Sprintf(":%d", setting.HTTPPort),
		Handler:        router,
		ReadTimeout:    setting.ReadTimeout,
		WriteTimeout:   setting.WriteTimeout,
		MaxHeaderBytes: 1 << 20,
	}

	go func() {
		if err := s.ListenAndServe(); err != nil {
			log.Println("listen:", err)
		}
	}()

	quit := make(chan os.Signal)
	signal.Notify(quit, os.Interrupt)
	<-quit

	log.Println("Server Shutdown")

	ctx, cancel := context.WithTimeout(context.Background(), 5 * time.Second)
	defer cancel()
	if err := s.Shutdown(ctx); err != nil {
		log.Println("Shutdown:", err)
	}

	log.Println("Server Exit")
}

参考文档

标签:HTTP,log,fmt,http,Golang,setting,gin,Gin,ReadTimeout
来源: https://www.cnblogs.com/mayanan/p/16672808.html