核心知识点
- json配置文件解析成结构体
- 将路由对应的接口抽离到单独的文件中,main函数中直接注册路由即可
项目目录图
项目代码
{
"app_name": "cloudRestaurant",
"app_mode": "debug",
"app_host": "127.0.0.1",
"app_port": "8000"
}
package tool
import (
"bufio"
"encoding/json"
"fmt"
"os"
)
type Config struct {
AppName string `json:"app_name"`
AppMode string `json:"app_mode"`
AppHost string `json:"app_host"`
AppPort string `json:"app_port"`
}
var _cfg Config
func ParseConfig(path string) (*Config, error) {
// 解析配置文件
file, err := os.Open(path)
if err != nil {
panic(err.Error())
}
defer file.Close()
reader := bufio.NewReader(file)
decoder := json.NewDecoder(reader)
err = decoder.Decode(&_cfg) // 注意:要将和json对应的结构体指针传进来,而不是结构体对象
if err != nil {
fmt.Println(err.Error())
return nil, err
}
return &_cfg, nil
}
- HelloController.go文件,接口写在这里面
package controller
import (
"github.com/gin-gonic/gin"
"net/http"
)
type HelloController struct {}
func (h *HelloController) Router(engine *gin.Engine) {
engine.GET("/hello", h.Hello)
engine.POST("/hello", h.HelloP)
}
func(h *HelloController) HelloP(ctx *gin.Context) {
ctx.Writer.Write([]byte("post hello"))
}
func(h *HelloController) Hello(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{
"msg": "OK",
})
}
package main
import (
"CloudRestaurant/controller"
"CloudRestaurant/tool"
"fmt"
"github.com/gin-gonic/gin"
)
var (
config *tool.Config
)
func init() {
// 初始化配置文件
var err error
config, err = tool.ParseConfig("./config/app.json")
if err != nil {
fmt.Println(err.Error())
}
}
func main() {
app := gin.Default()
// 注册路由
registerRouter(app)
app.Run(config.AppHost + ":" + config.AppPort)
}
// 路由设置
func registerRouter(router *gin.Engine) {
new(controller.HelloController).Router(router)
}