gin api blog

Gin项目

介绍

以下是基于gin开发的项目接口,将持续更新,有兴趣请star,本项目包含mysql,redis,elasticsearch,mongo,rabbitmq,kafka,jaeger,单机限流,分布式限流,sentry, jwt,请求参数验证,发送邮件,图片上传,httpclient用于请求第三方接口等,为了减少手动写model结构体的痛苦,可以看我另外一个仓库https://github.com/Eric-chy/generate-models 自动生成model文件,后面会补上grpc的部分,另外可以关注我的博客http://www.cyz.show 以下3-6所有组件的安装可以参考我的博客:http://www.cyz.show/article/45

目录结构

ginpro  根目录
├─boot  初始化启动数据库连接等
├─common  初始化启动数据库连接等
│   ├─dict   数据字典,错误码和常用参数
│   └─global 全局变量    
├─config 系统配置文件目录
│   ├─config.go  配置初始化
│   ├─dev.yaml   开发机配置
│   └─qa.yaml   测试环境配置    
├─docs  swagger文档目录(下面三个文件在根目录swag init命令生成)
│  ├─docs.go            
│  ├─swagger.json            
│  └─swagger.yaml
├─internal  
│  ├─api  接口                    
│  ├─dao dao层,对数据库的增删改查            
│  ├─middleware 中间件            
│  ├─model model层,数据库字段表名等            
│  ├─router 路由            
│  └─service 
├─pkg  
│  ├─app  接口     
│  │  ├─app.go 接口响应等方法封装        
│  │  ├─form.go 表单验证封装            
│  │  ├─jwt.go jwt鉴权            
│  │  └─pagination.go 分页  
│  ├─es elasticsearch  
│  ├─fasthttp    
│  ├─gredis  redis    
│  ├─helper
│  │  ├─convert 常用转换        
│  │  ├─email 邮件发送            
│  │  ├─files 文件操作相关            
│  │  ├─gjson json操作            
│  │  └─gtime 时间相关操作  
│  ├─limiter 限流            
│  ├─logger 日志                   
│  ├─mgodb mongodb                   
│  ├─rabbitmq rabbitmq                   
│  ├─security md5加密等                       
│  └─tracer 链路追踪
├─storage               
│  ├─logs 日志            
│  └─uploads  上传的文件 
├─go.mod   模块管理   
└─main.go 入口文件

启动教程

  1. 安装mysql
  2. 安装jaeger:
    docker run -d --name jaeger \
    -e COLLECTOR_ZIPKIN_HTTP_PORT=9411 \
    -p 5775:5775/udp \
    -p 6831:6831/udp \
    -p 6832:6832/udp \
    -p 5778:5778 \
    -p 16686:16686 \
    -p 14268:14268 \
    -p 9411:9411 \
    jaegertracing/all-in-one:latest
  3. 安装es(以下3-6都可以通过在boot/boot.go的InitApp方法中选择决定初始化是否安装,如果不需要可以注释掉对应代码)
  4. 安装redis
  5. 安装mongo
  6. 安装rabbitmq
  7. 安装sentry,如果不想安装,请修改pkg/logger/logrus.go文件中的下面代码注释掉,安装可以参考我的博客:http://www.cyz.show/article/37#content
    hook, err := logrus_sentry.NewSentryHook(config.Conf.Sentry.Dsn, []logrus.Level{
    logrus.PanicLevel,
    logrus.FatalLevel,
    logrus.ErrorLevel,
    })
    if err == nil {
    global.Logger.Hooks.Add(hook)
    hook.Timeout = 0
    hook.StacktraceConfiguration.Enable = true
    }
  8. 在项目根目录下执行go mod tidy
  9. go run main.go即可启动
  10. 为了方便开发,一般使用热更新,安装fresh,在根目录下执行go get github.com/pilu/fresh,然后使用fresh命令即可启动,和上面第9步骤二选一
  11. swagger安装,生成文档,非必需
    go get -u github.com/swaggo/swag/cmd/[email protected] 
    go get -u github.com/swaggo/[email protected]
    go get -u github.com/swaggo/files
    go get -u github.com/alecthomas/template
    
    验证是否安装成功: swag -v 对controller即接口进行注解
    // @Summary 获取列表
    // @Produce  json
    // @Param name query string false "名称" maxlength(100)
    // @Param state query int false "状态" Enums(0, 1) default(1)
    // @Param page query int false "页码"
    // @Param page_size query int false "每页数量"
    // @Success 200 {object} model.Tag "成功"
    // @Failure 400 {object} code.Error "请求错误"
    // @Failure 500 {object} code.Error "内部错误"
    // @Router /api/list [get]
    func (c *Controller) List (c *gin.Context) {
        app.Success(c, nil)
    }
    区分项目的话,在main入口函数添加注解:
    // @title gin系统
    // @version 1.0
    // @description gin开发的系统
    // @termsOfService 
    func main(){}
    在model文件中添加
    type ArticleSwagger struct {
        List  []*Article
        Pager *app.Pager
    }
    
    设置路由,在apiRouter.go中先(否则会报:Failed to load spec)
    import(
        _ "ginpro/docs"
    )
    
    再设置
    r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
    
    生成swagger文档:在根目录执行swag init swagger文档查看 http://127.0.0.1:8001/swagger/index.html查看 11.如果不需要其中的某些组件,如es,redis,mongo等,可以在boot/boot.go init方法中注释掉相关的即可

使用说明

  1. 启动项目后我们可以看到对应的路由信息,可以使用浏览器或者postman之类的进行访问
  2. 链路信息查看:http://127.0.0.1:16686/
  3. 文件上传测试 curl -X POST http://127.0.0.1:8000/upload/file -F file=@{file_path} -F type=1
  4. 项目启动后访问 http://127.0.0.1:8088/api/articles
  5. 建表语句,目前只是简单展示,所以只建立了一个简单的表
CREATE DATABASE blog;
USE blog;
CREATE TABLE `article` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`introduction` varchar(500) COLLATE utf8mb4_unicode_ci,
`views` int(11) NOT NULL DEFAULT '0',
`content` varchar(5000) COLLATE utf8mb4_unicode_ci,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=Innodb DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
INSERT INTO blog.article VALUES(NULL, "我的第一篇文章", "文章简介", 100, "文章的内容很好看", "2020-02-02 02:22:22", "2020-02-02 02:22:22") 
Similar Resources

Golang beego framework based personal simple blog system

Golang beego framework based personal simple blog system

goblog 基于Golang的个人简易博客系统 [TOC] goblog介绍 goblog基于go语言开发的一个简约版个人博客系统,基于Golang语言编写,后端基于了Beego的web框架,目前具备博文系统最基础的功能模块.基本上是一个拿来即用的个人博文平台,只需要部署一个mysql数据存储服务

Nov 9, 2021

Blog backend system based on GO

个人博客后端文档 简介 相关功能 v0.1 用户登录、注册 文章发布、查看、评论、点赞 粉丝相关(关注) v0.2 排行榜(文章发布数量、粉丝) v0.3 流量统计 技术栈 语言选用go 大致技术栈选用: kratos + redis + jwt + gorm 项目地址 todo 项目结构

Nov 26, 2021

Blog backend based on go implementation

个人博客后端文档 简介 相关功能 v0.1 用户登录、注册 文章发布、查看、评论、点赞 粉丝相关(关注) v0.2 排行榜(文章发布数量、粉丝) v0.3 流量统计 技术栈 语言选用go 大致技术栈选用: kratos + redis + jwt + gorm 项目地址 todo 项目结构

Dec 4, 2021

An implementation of a backend blog microservice written in go.

Blog This is an implementation of the backend of a blog service written in Go 1.17 created with a microservice architecture in mind. Currently impleme

Dec 9, 2021

A blog system implemented via golang.

goblog functions work as a blog site read/write blogs signup/signin/logout vote with stars 1~5 user admin: add ranks to users: bronze, silver, gold wo

Jan 5, 2022

DCreater - Build your own blog system with golang

DCreater - Build your own blog system with golang

Aug 18, 2022

Blog - Exploring Domain Driven Design In Go

Exploring Domain Driven Design In Go

Jan 25, 2022

Simple Go BE to serve blog posts

Simple Go BE to serve blog posts

Jan 25, 2022

Api-go-gin-viper - Simple representaion on how to implement CRUD functionality in API using Go programming language

Simple API implementaion in Go To Get Started Clone repo Run the command to clon

Feb 18, 2022
Comments
  • 拉取代码执行完会报错

    拉取代码执行完会报错

    { "code": 10000000, "msg": "服务内部错误", "data": null, "elapsed": 0.00009228 }

    #File:logger.go:27 #Msg:[错误信息::runtime error: invalid memory address or nil pointer dereference] #Content:{"header":{"Accept":["text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,/;q=0.8,application/signed-exchange;v=b3;q=0.9"],"Accept-Encoding":["gzip, deflate, br"],"Accept-Language":["zh-CN,zh;q=0.9"],"Cache-Control":["max-age=0"],"Connection":["keep-alive"],"Cookie":["grafana_session=719e9283b15169a149300885ffe955fa"],"Sec-Ch-Ua":[""Chromium";v="106", "Google Chrome";v="106", "Not;A=Brand";v="99""],"Sec-Ch-Ua-Mobile":["?0"],"Sec-Ch-Ua-Platform":[""macOS""],"Sec-Fetch-Dest":["document"],"Sec-Fetch-Mode":["navigate"],"Sec-Fetch-Site":["none"],"Sec-Fetch-User":["?1"],"Upgrade-Insecure-Requests":["1"],"User-Agent":["Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36"]},"ip":"127.0.0.1","method":"GET","proto":"HTTP/1.1","request":"","response":{"code":10000000,"msg":"服务内部错误","data":null,"elapsed":0.000051408},"url":"127.0.0.1:8888/"} 【ERROR】 [2022-10-15 10:43:22] [ip:127.0.0.1] [GID:24] [RID:1665816202215879]

gin api blog

Gin项目 介绍 以下是基于gin开发的项目接口,将持续更新,有兴趣请star,本项目包含mysql,redis,elasticsearch,mongo,rabbitmq,kafka,jaeger,单机限流,分布式限流,sentry, jwt,请求参数验证,发送邮件,图片上传,httpclient用

Oct 14, 2022
A simple blog based on gin framework

gin-blog 介绍 a simple blog based on gin framework 软件架构 MySQL/MariaDB as database 安装教程 基于Docker启动MySQL/MariaDB 使用说明 启动MySQL in Docker. 参与贡献 Fork 本仓库 新建

Nov 15, 2021
Go (Golang) API REST with Gin FrameworkGo (Golang) API REST with Gin Framework

go-rest-api-aml-service Go (Golang) API REST with Gin Framework 1. Project Description Build REST APIs to support AML service with the support of exte

Nov 21, 2021
Go-gin-mongo-api - A backend RESTful API built using golang, gin and mongoDB

go-gin-mongo-API This is a RESTful backend API which is developed using the gola

Jul 19, 2022
Gin-easy-todo - golang 의 RESTful API 프레임워크 gin 을 활용해 아주 간단한 Todo 애플리케이션을 만들어보자.
Gin-easy-todo - golang 의 RESTful API 프레임워크 gin 을 활용해 아주 간단한 Todo 애플리케이션을 만들어보자.

목차 1. 요약 2. 목표 3. API 목록 4. 프로젝트 구조 5. 패키지 별 기능과 관계 6. 사전 작업 6.1. DB, Table 생성 6.2. 모듈 생성 6.3. 패키지 다운로드 7. Gin 작성 7.1. 데이터베이스 설정 7.2. 테이블, 스키마 정의 7.3.

Jan 2, 2022
Go-service-gin - Simple Web api application developed in Golang and Gin

Simple Web api application developed in Golang and Gin Initial Tutorial URL http

Jan 4, 2022
Go-gin-ddd-cqrs - Clean api rest with Go, Gin and GORM
Go-gin-ddd-cqrs - Clean api rest with Go, Gin and GORM

GOLANG API REST Clean api rest with Go, Gin and GORM. Clean Architecture with DD

Oct 21, 2022
Gin-boilerplate - Gin boilerplate preconfigured with basic rest api features

Gin Boilerplate Build apis with gin faster with this template Features Validatio

Jun 24, 2022
Gin-boilerplate - This repository contains boilerplate code of a REST service using Gin (golang) framework.

Boilerplate REST service using Gin web framework (golang) Introduction This repository contains a boilerplate REST API service using Gin web framework

Apr 28, 2022
Hosting of the "Programming DIY / Программирование - это просто!" blog

This repository contains materials of the personal blog "Программирование - это просто / Programming DIY". How to use the blog engine A blog post abou

Jul 15, 2022