feat: add gweb
This commit is contained in:
parent
d6dfb47547
commit
f1e5d57257
71
gweb/gin.go
Normal file
71
gweb/gin.go
Normal file
@ -0,0 +1,71 @@
|
||||
//
|
||||
// gin.go
|
||||
// Copyright (C) 2023 tiglog <me@tiglog.com>
|
||||
//
|
||||
// Distributed under terms of the MIT license.
|
||||
//
|
||||
|
||||
package gweb
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type Engine = gin.Engine
|
||||
|
||||
type Context = gin.Context
|
||||
|
||||
type H = gin.H
|
||||
|
||||
func RunWeb(app *Engine, addr string) {
|
||||
if addr[0] == ':' {
|
||||
addr = "127.0.0.1" + addr
|
||||
}
|
||||
srv := &http.Server{
|
||||
Addr: addr,
|
||||
Handler: app,
|
||||
ReadTimeout: 10 * time.Second,
|
||||
WriteTimeout: 10 * time.Second,
|
||||
MaxHeaderBytes: 1 << 20,
|
||||
}
|
||||
|
||||
log.Printf("start web server http://%s ...\n", srv.Addr)
|
||||
go func() {
|
||||
var err error
|
||||
err = srv.ListenAndServe()
|
||||
if err != nil && errors.Is(err, http.ErrServerClosed) {
|
||||
log.Printf("listen: %s\n", err)
|
||||
}
|
||||
}()
|
||||
|
||||
// Wait for interrupt signal to gracefully shutdown the server with
|
||||
// a timeout of 5 seconds.
|
||||
quit := make(chan os.Signal)
|
||||
// kill (no param) default send syscall.SIGTERM
|
||||
// kill -2 is syscall.SIGINT
|
||||
// kill -9 is syscall.SIGKILL but can't be caught, so don't need to add it
|
||||
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
|
||||
<-quit
|
||||
log.Print("Shutting down server...")
|
||||
|
||||
// The context is used to inform the server it has 5 seconds to finish
|
||||
// the request it is currently handling
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := srv.Shutdown(ctx); err != nil {
|
||||
log.Fatalf("Server forced to shutdown with err %s.", err.Error())
|
||||
}
|
||||
|
||||
log.Print("Server exiting")
|
||||
|
||||
}
|
Loading…
Reference in New Issue
Block a user