gin项目最佳实践

Gin Rest gorm 大型项目最佳实践 在使用 GORM 构建大型项目时,以下是一些最佳实践,可以帮助提高项目的可维护性和可扩展性。 项目结构 清晰的项目结构是保证项目可维护性的关键。以下是一个推荐的项目结构: go 复制代码 ├── config // 配置文件 │ └── config.go ├── controllers // 控制器 │ └── userController.go ├── middlewares // 中间件 │ └── authMiddleware.go ├── models // 模型 │ └── user.go ├── repositories // 数据访问层 │ └── userRepository.go ├── services // 服务层 │ └── userService.go ├── routes // 路由 │ └── routes.go ├── utils // 工具函数 │ └── logger.go ├── main.go // 主程序入口 └── go....

2020-06-21 · 3 分钟 · 553 字 · Me

gin请求

1. Get 请求参数 使用 Get 请求传参时,类似于这样 http://localhost:8080/user/save?id=11&name=zhangsan。 如何获取呢? 1.1 普通参数 request url: http://localhost:8080/user/save?id=11&name=zhangsan r.GET("/user/save", func(ctx *gin.Context) { id := ctx.Query("id") name := ctx.Query("name") ctx.JSON(200, gin.H{ "id": id, "name": name, }) }) 如果参数不存在,就给一个默认值: r.GET("/user/save", func(ctx *gin.Context) { id := ctx.Query("id") name := ctx.Query("name") address := ctx.DefaultQuery("address", "北京") ctx.JSON(200, gin.H{ "id": id, "name": name, "address": address, }) }) 判断参数是否存在: r.GET("/user/save", func(ctx *gin.Context) { id, ok := ctx.GetQuery("id") address, aok := ctx.GetQuery("address") ctx.JSON(200, gin....

2019-09-01 · 3 分钟 · 431 字 · Me

gin简单使用

两种启动方式 方式一 package main import ( "github.com/gin-gonic/gin" "net/http" ) func main() { router := gin.Default() router.GET("/", func(c *gin.Context) { c.String(http.StatusOK, "Hello World") }) // 启动监听,gin会把web服务运行在本机的0.0.0.0:8080端口上 router.Run("0.0.0.0:8080") } 方式二 package main import ( "github.com/gin-gonic/gin" "net/http" ) func Index(context *gin.Context) { context.String(200, "gin demo!") } func main() { // 创建一个默认的路由 router := gin.Default() // 绑定路由规则和路由函数,访问/index的路由,将由对应的函数去处理 router.GET("/index", Index) // 用原生http服务的方式, router.Run本质就是http.ListenAndServe的进一步封装 // 可以自定义优雅关闭 http.ListenAndServe(":8080", router) } 方式二的变异 // 上面的变异方式; 部分代码片段 router := initialize.Routers() srv := http....

2019-08-02 · 2 分钟 · 219 字 · Me