章工运维 章工运维
首页
  • linux
  • windows
  • 中间件
  • 监控
  • 网络
  • 存储
  • 安全
  • 防火墙
  • 数据库
  • 系统
  • docker
  • 运维工具
  • other
  • elk
  • K8S
  • ansible
  • Jenkins
  • GitLabCI_CD
  • 随笔
  • 面试
  • 工具
  • 收藏夹
  • Shell
  • python
  • golang
友链
  • 索引

    • 分类
    • 标签
    • 归档
    • 首页 (opens new window)
    • 关于我 (opens new window)
    • 图床 (opens new window)
    • 评论 (opens new window)
    • 导航栏 (opens new window)
周刊
GitHub (opens new window)

章工运维

业精于勤,荒于嬉
首页
  • linux
  • windows
  • 中间件
  • 监控
  • 网络
  • 存储
  • 安全
  • 防火墙
  • 数据库
  • 系统
  • docker
  • 运维工具
  • other
  • elk
  • K8S
  • ansible
  • Jenkins
  • GitLabCI_CD
  • 随笔
  • 面试
  • 工具
  • 收藏夹
  • Shell
  • python
  • golang
友链
  • 索引

    • 分类
    • 标签
    • 归档
    • 首页 (opens new window)
    • 关于我 (opens new window)
    • 图床 (opens new window)
    • 评论 (opens new window)
    • 导航栏 (opens new window)
周刊
GitHub (opens new window)
  • python

  • shell

  • go

    • go基础

      • 指针
      • 数组
      • 切片
      • 字典
      • 结构体
      • 匿名组合
      • 方法
      • 接口
      • error接口
      • panic使用
    • Init函数和main函数
    • 下划线
    • go报错问题收集
    • Redis和MySQL结合的Web服务示例
    • go定义json数据
    • 使用go和vue编写学生管理系统
    • gin框架探索
  • 编程
  • go
章工运维
2024-11-17

gin框架探索

# gin框架结构

gin-demo/
├── config/ #配置文件
│   └── config.go 
├── controllers/ #    控制器层:处理请求和响应
│   └── data_controller.go
├── logic/ # 业务逻辑层:处理业务规则
│   └── data_logic.go
├── models/ # 模型层:数据结构定义
│   └── data.go
├── services/ #服务层:数据操作
│   └── data_service.go
├── routes/ #路由层
│   └── router.go
├── go.mod
└── main.go # 入口文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

编写代码循序

先写配置config

package config

const (
    ServerPort = ":8001"
)
1
2
3
4
5

models

package models

type Data struct {
    ID      int    `json:"id"`
    Content string `json:"content"`
}

// 模拟数据存储
var DataList []Data
var CurrentID = 0 
1
2
3
4
5
6
7
8
9
10

services

package services

import (
    "gin-demo/models"
)

type DataService struct{}

func NewDataService() *DataService {
    return &DataService{}
}

func (s *DataService) AddData(content string) models.Data {
    models.CurrentID++
    newData := models.Data{
        ID:      models.CurrentID,
        Content: content,
    }
    models.DataList = append(models.DataList, newData)
    return newData
}

func (s *DataService) GetAllData() []models.Data {
    return models.DataList
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

logic

package logic

import (
    "errors"
    "gin-demo/models"
    "gin-demo/services"
    "sort"
)

type DataLogic struct {
    dataService *services.DataService
}

func NewDataLogic() *DataLogic {
    return &DataLogic{
        dataService: services.NewDataService(),
    }
}

// AddData 处理添加数据的业务逻辑
func (l *DataLogic) AddData(content string) (models.Data, error) {
    // 业务规则验证
    if content == "" {
        return models.Data{}, errors.New("content cannot be empty")
    }

    if len(content) > 100 {
        return models.Data{}, errors.New("content too long, maximum 100 characters")
    }

    // 调用service层添加数据
    return l.dataService.AddData(content), nil
}

// GetAllData 处理获取数据的业务逻辑
func (l *DataLogic) GetAllData() []models.Data {
    data := l.dataService.GetAllData()

    // 按ID倒序排序
    sort.Slice(data, func(i, j int) bool {
        return data[i].ID > data[j].ID
    })

    return data
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

controllers

package controllers

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

type DataController struct {
    dataLogic *logic.DataLogic
}

func NewDataController() *DataController {
    return &DataController{
        dataLogic: logic.NewDataLogic(),
    }
}

func (c *DataController) AddData(ctx *gin.Context) {
    var request struct {
        Content string `json:"content" binding:"required"`
    }

    if err := ctx.BindJSON(&request); err != nil {
        ctx.JSON(http.StatusBadRequest, gin.H{
            "error": "Invalid request data",
            "details": err.Error(),
        })
        return
    }

    newData, err := c.dataLogic.AddData(request.Content)
    if err != nil {
        ctx.JSON(http.StatusBadRequest, gin.H{
            "error": err.Error(),
        })
        return
    }

    ctx.JSON(http.StatusOK, gin.H{
        "message": "数据添加成功",
        "data":    newData,
    })
}

func (c *DataController) GetData(ctx *gin.Context) {
    data := c.dataLogic.GetAllData()
    ctx.JSON(http.StatusOK, data)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

routes

package routes

import (
    "gin-demo/controllers"
    "github.com/gin-gonic/gin"
)

func SetupRouter() *gin.Engine {
    r := gin.Default()

    // CORS中间件
    r.Use(func(c *gin.Context) {
        c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
        c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
        c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type")

        if c.Request.Method == "OPTIONS" {
            c.AbortWithStatus(204)
            return
        }

        c.Next()
    })

    dataController := controllers.NewDataController()

    api := r.Group("/req")
    {
        api.POST("/post", dataController.AddData)
        api.GET("/get", dataController.GetData)
    }

    return r
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

main.go

package main

import (
    "gin-demo/config"
    "gin-demo/routes"
)

func main() {
    r := routes.SetupRouter()
    r.Run(config.ServerPort)
}    
1
2
3
4
5
6
7
8
9
10
11
微信 支付宝
上次更新: 2024/11/17, 19:51:51

← 使用go和vue编写学生管理系统

最近更新
01
shell脚本模块集合
05-13
02
生活小技巧(认知版)
04-29
03
生活小技巧(防骗版)
04-29
更多文章>
Theme by Vdoing | Copyright © 2019-2025 | 点击查看十年之约 | 鄂ICP备2024072800号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式