gin + vue3 搭建博客系统(2)gin服务启动

173 阅读1分钟

一、安装 gin

使用 go get github.com/gin-gonic/gin 安装 使用import导入gin

二、服务注册

在bootstrap新建route.go

import (
   "fmt"
   "net/http"
   
   "gin-blog/global"

   "github.com/gin-gonic/gin"
)


func InitialServer() {
   r := gin.Default()
   srv := &http.Server{
      Addr:    ":" + global.Config.App.Port,
      Handler: r,
   }
   if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
      panic(any(fmt.Errorf("服务启动失败,err:%v",err)))
   }
   
}

三、路由管理

在router目录新建route.go

package router

import (
   "gin-blog/api"
   "github.com/gin-gonic/gin"
)

func UserRoute(route *gin.RouterGroup)  {
   route.GET("/user",api.User.GetUser)
}

在api目录新建user.go

package api

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

type user struct {

}
var User = new(user)

func (u user) GetUser(c *gin.Context)  {
   c.JSON(http.StatusOK, "hello world")
}

在bootstrap/route.go 的InitialServe 添加

apiGroup := r.Group("/api")

router.UserRoute(apiGroup)

服务启动

在main函数调用InitialServe(),启动项目

image.png 在浏览器访问 http://localhost:9999/api/user

image.png