Coder Social home page Coder Social logo

baxibaba / gen Goto Github PK

View Code? Open in Web Editor NEW

This project forked from wangbjun/gen

0.0 0.0 0.0 175 KB

基于Gin框架开发的脚手架工具,便于使用Go快速开发接口,集成数据库、日志、配置等开源库,开箱即用

License: Apache License 2.0

Go 100.00%

gen's Introduction

Gen Web - 基于Gin框架封装的脚手架工具,便于用Go快速开发Web API

介绍

主要使用以下开源组件:

项目目录结构清晰明了,简单易用,快速上手,包含了一个用户注册、登录、文章增删改查等功能的 Restful API 应用,仅供参考!

主要包含以下API:

METHOD URI DESCRIPTION
GET / 默认首页
POST /api/v1/user/register 用户注册
POST /api/v1/user/login 用户登录
POST /api/v1/user/logout 用户登出
GET /api/v1/articles 文章列表
POST /api/v1/articles 发布文章
GET /api/v1/articles/:id 文章详情
PUT /api/v1/articles/:id 修改文章
DELETE /api/v1/articles/:id 删除文章
POST /api/v1/articles/:id/comments 添加文章评论

架构

项目采用了依赖注入的方式贯穿全局,我们可以把DB、缓存、HTTP API等功能看作是项目的一个服务,通过facebook开源的inject库,我们在启动项目把这些Service注入进去,解决各自之间的依赖关系。

type ArticleService struct {
    SQLStore *SQLService         `inject:""`
    Cache    *cache.CacheService `inject:""`
}

func init() {
    registry.RegisterService(&ArticleService{})
}

func (r ArticleService) Init() error {
    return nil
}

既灵活,也不影响性能,因为虽然依赖注入使用了反射,但是我们只在程序启动之前做这件事,而且只需要进行一次。

启动流程

main文件是程序的入口,主要功能是解析命令行参数,只有一个参数,那就是配置文件,默认配置文件是当前目录下的app.ini

紧接着,创建一个Server实例:

// Server is responsible for managing the lifecycle of services.
type Server struct {
    context          context.Context
    shutdownFn       context.CancelFunc
    childRoutines    *errgroup.Group
    log              *zap.Logger
    cfg              *config.Cfg    // 项目配置
    shutdownOnce     sync.Once
    shutdownFinished chan struct{}
    isInitialized    bool
    mtx              sync.Mutex
    serviceRegistry  serviceRegistry // 注册的服务
}

这个Server实例是管理所有服务的中心,其主要工作就是加载配置文件,然后根据配置文件初始化日志配置,日志库采用zap log,主要文件在zap/zap_logger.go里面

然后还有一个最重要是就是初始化所有注册过服务,执行其Init方法做一些初始化工作,最后执行后台服务。

如果一个服务实现了Run方法,就是一个后台服务,会在项目启动时候运行,结束时候优雅关闭,其中最好的例子就是HTTPServer,我们可以把API服务认为是一个后台服务,在整个项目启动的时候就会运行。

type HTTPServer struct {
    log     *zap.Logger
    gin     *gin.Engine
    context context.Context

    Cfg            *config.Cfg             `inject:""`
    ArticleService *article.ArticleService `inject:""`
    UserService    *user.UserService       `inject:""`
}

HTTPServer的代码在api/http_server.go文件里面,其主要作用就是初始化一些服务配置,然后启动HTTP服务,使用了Gin框架。

代码介绍

services文件夹下包含了一些服务的代码文件。

项目整体是一个3层架构,即控制器层、Service层、模型层。

个人理解,控制器层主要做一些接口参数校验等工作,模型层主要是数据操作,Service层才是主要的业务逻辑。

数据库相关配置在models/db.go里面,也是一个服务,主要作用是根据配置,初始化数据库连接,支持多数据库配置、支持Sql日志记录。

type SQLService struct {
    Cfg *config.Cfg `inject:""`

    conns map[string]*gorm.DB
    log   *zap.Logger
}

func DB(dbName ...string) *gorm.DB {
    if len(dbName) > 0 {
        if conn, ok := sqlStore.conns[dbName[0]]; ok {
            return conn
        }
    }
    return db
}

项目使用了Gorm(2.0版本),具体详细用法可以参考官方文档。

路由文件位于api/api.go,可以多层嵌套,中间件在middleware文件夹。

config/config.go是配置文件的一些加载逻辑,可以根据自己需求适当的修改优化。

关于接口参数,建议POST、PUT统一使用JSON形式,在模型层里面定义好相应的结构体,参数的校验采用了go-playground/validator/v10库,直接在结构体Tag里面标记即可,详细用法请参考其官方文档。

type CreateArticleCommand struct {
    Id      int
    UserId  int
    Title   string `form:"title" json:"title" binding:"gt=1,lt=100"`
    Content string `form:"content" json:"content" binding:"gt=1,lt=2000"`
}

type UpdateArticleCommand struct {
    Id      int
    UserId  int
    Title   string `form:"title" json:"title" binding:"gt=1,lt=100"`
    Content string `form:"content" json:"content" binding:"gt=1,lt=2000"`
}

使用

建议直接clone本项目,然后删除多余的控制器、模型等文件,根据自己需求调整即可。

2021-07-04 12:49:19     debug   Service [SqlService] init success
2021-07-04 12:49:19     debug   Service [HTTPServer] init success
2021-07-04 12:49:19     debug   Service [UserService] init success
2021-07-04 12:49:19     debug   Service [CacheService] init success
2021-07-04 12:49:19     debug   Service [ArticleService] init success
2021-07-04 12:49:19     debug   Waiting on services...  {"module": "server"}
2021-07-04 12:49:19     debug   Server was started successfully {"module": "http_server"}

最后的最后,本项目参考借鉴了著名Go开源项目 Grafana 的设计和架构,这个项目的后端是全部采用Go开发,东西也很多,代码很不错。

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.