preface

This article will group routes, centralize the files that define routes into the same directory, and deal with the static files packaged with the front-end project. In Go 1.8 and above, the built-in HTTP. Server provides the Shutdown() method, which supports a smooth restart of the Server. This time, we will use it to adjust the project startup code

Route Group Adjustment

Create the routes/api.go file to store API group routes

package routes

import (
    "github.com/gin-gonic/gin"
    "net/http"
)

// SetApiGroupRoutes defines API packet routing
func SetApiGroupRoutes(router *gin.RouterGroup) {
    router.GET("/ping".func(c *gin.Context) {
        c.String(http.StatusOK, "pong")})}Copy the code

Create the bootstrap/router.go file and write

package bootstrap

import (
    "github.com/gin-gonic/gin"
    "jassue-gin/global"
    "jassue-gin/routes"
)

func setupRouter(a) *gin.Engine {
    router := gin.Default()

    // Register API packet routing
    apiGroup := router.Group("/api")
    routes.SetApiGroupRoutes(apiGroup)

    return router
}

// RunServer starts the server
func RunServer(a) {
    r := setupRouter()
    r.Run(":" + global.App.Config.App.Port)
}
Copy the code

If there are other grouped routes, you can create a file in the routes directory, write a route definition method, and then call bootstrap/router.go to register the route

Call the RunServer() method in the main.go file

package main

import (
    "jassue-gin/bootstrap"
    "jassue-gin/global"
)

func main(a) {
    // Initialize the configuration
    bootstrap.InitializeConfig()

    // Initialize the log
    global.App.Log = bootstrap.InitializeLog()
    global.App.Log.Info("log init success!")

    // Initialize the database
    global.App.DB = bootstrap.InitializeDB()
    // Release the database connection before closing the program
    defer func(a) {
        ifglobal.App.DB ! =nil {
            db, _ := global.App.DB.DB()
            db.Close()
        }
    }()

    // Start the server
    bootstrap.RunServer()
}
Copy the code

Static resource processing

In the bootstrap/router.go file, setupRouter() method:

func setupRouter(a) *gin.Engine {
    router := gin.Default()

    // Front-end project static resources
    router.StaticFile("/"."./static/dist/index.html")
    router.Static("/assets"."./static/dist/assets")
    router.StaticFile("/favicon.ico"."./static/dist/favicon.ico")
    // Other static resources
    router.Static("/public"."./static")
    router.Static("/storage"."./storage/app/public")

    // Register API packet routing
    apiGroup := router.Group("/api")
    routes.SetApiGroupRoutes(apiGroup)

    return router
}
Copy the code

Use Docker to quickly package a front-end project file:

#Create the Node environment container
docker run -idt --name vue-app jassue/node
#Into the container
docker exec -it vue-app bash
#Initialize the VUE template
npm init @vitejs/app . --template vue-ts
#Installation project dependencies
npm install
#packaging
npm run build
#Out of the container
exit
#Copy the front-end files to the GO project static resources folder
docker cp vue-app:/app/dist ~/go/src/jassue-gin/static
Copy the code

Go is started, and http://localhost:8888/ is accessed. Front-end resources are processed successfully

Uya restarts/stops the server

In the bootstrap/router.go file, adjust the RunServer() method

package bootstrap

import (
    "context"
    "github.com/gin-gonic/gin"
    "jassue-gin/global"
    "jassue-gin/routes"
    "log"
    "net/http"
    "os"
    "os/signal"
    "syscall"
    "time"
)

/ /...

func RunServer(a) {
   r := setupRouter()

   srv := &http.Server{
       Addr:    ":" + global.App.Config.App.Port,
       Handler: r,
   }

   go func(a) {
       iferr := srv.ListenAndServe(); err ! =nil&& err ! = http.ErrServerClosed { log.Fatalf("listen: %s\n", err)
       }
   }()

   // Wait for an interrupt signal to gracefully shut down the server (set a timeout of 5 seconds)
   quit := make(chan os.Signal)
   signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
   <-quit
   log.Println("Shutdown Server ...")

   ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
   defer cancel()
   iferr := srv.Shutdown(ctx); err ! =nil {
       log.Fatal("Server Shutdown:", err)
   }
   log.Println("Server exiting")}Copy the code

In routes/api.go, add a test route:

router.GET("/test".func(c *gin.Context) {
    time.Sleep(5*time.Second)
    c.String(http.StatusOK, "success")})Copy the code

Start main. Go to http://localhost:8888/api/test, use CTRL + C to stop the server, as shown in the figure below:

After receiving the abort command, the server still waits for the/API /test interface to complete the response before stopping the server