init
This commit is contained in:
55
main.go
Executable file
55
main.go
Executable file
@@ -0,0 +1,55 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"time"
|
||||
"video/router"
|
||||
)
|
||||
|
||||
func main() {
|
||||
r := router.InitRouter()
|
||||
host := "0.0.0.0"
|
||||
port := "10001"
|
||||
srv := initServer(host, port, r)
|
||||
|
||||
// 启动服务
|
||||
go startServer(srv, host, port)
|
||||
|
||||
// 优雅关闭
|
||||
gracefulShutdown(srv)
|
||||
}
|
||||
|
||||
func initServer(host, port string, handler http.Handler) *http.Server {
|
||||
return &http.Server{
|
||||
Addr: fmt.Sprintf("%s:%s", host, port),
|
||||
Handler: handler,
|
||||
ReadTimeout: 60 * time.Second,
|
||||
WriteTimeout: 60 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
func startServer(srv *http.Server, host, port string) {
|
||||
fmt.Println("Listening and serving HTTP on", host, ":", port)
|
||||
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
fmt.Printf("listen: %s\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
func gracefulShutdown(srv *http.Server) {
|
||||
quit := make(chan os.Signal, 1)
|
||||
signal.Notify(quit, os.Interrupt)
|
||||
<-quit
|
||||
fmt.Println("Shutdown Server ...")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if err := srv.Shutdown(ctx); err != nil {
|
||||
fmt.Println("Server Shutdown:", err)
|
||||
}
|
||||
fmt.Println("Server exiting")
|
||||
}
|
||||
Reference in New Issue
Block a user