zdpgo_api

package module
v1.1.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 17, 2022 License: MIT Imports: 19 Imported by: 0

README

zdpgo_api

基于gin二次封装的一个后端api快速开发框架

项目地址:https://github.com/zhangdapeng520/zdpgo_api

版本历史

  • v1.0.0 2022/2/9
  • v1.0.1 2022/2/11 指定默认模板目录template和默认静态文件夹目录static
  • v1.0.2 2022/2/11 移除本地依赖
  • v1.0.3 2022/2/11 新增日志中间件和recover中间件
  • v1.0.4 2022/3/8 优化模板和静态目录
  • v1.0.5 2022/3/8 增加常用的统一返回对象
  • v1.0.6 2022/3/8 将挂载通用路由设置为开关量
  • v1.0.7 2022/3/10 支持配置服务相关参数
  • v1.0.8 2022/3/10 支持viper读取和设置配置
  • v1.0.9 2022/3/11 logger日志支持配置
  • v1.1.0 2022/3/12 修复日志不打印body
  • v1.1.1 2022/4/8 新增详细日志
  • v1.1.2 2022/4/11 详细日志升级,支持查看的具体Body中的JSON数据
  • v1.1.3 2022/4/21 文件上传
  • v1.1.4 2022/5/16 新增:Api核心对象
  • v1.1.5 2022/5/17 优化:日志中间件优化
  • v1.1.6 2022/5/17 新增:添加静态文件服务
  • v1.1.7 2022/5/17 新增:API分组

示例

基本用法
package main

import (
	"embed"
	"github.com/zhangdapeng520/zdpgo_api"
	"net/http"
)

func ping(c *zdpgo_api.Context) {
	c.JSON(http.StatusOK, zdpgo_api.JsonMap{
		"code":    10000,
		"message": "success",
	})
}

// 设置路由
func setupRouter() *zdpgo_api.Api {
	api := zdpgo_api.NewWithConfig(zdpgo_api.Config{
		Debug: true,
	})

	// 常用方法 ping路由
	api.Get("/ping", ping)
	api.Post("/ping", ping)
	api.Put("/ping", ping)
	api.Delete("/ping", ping)
	api.Patch("/ping", ping)

	// 基本的权限校验路由
	authorized := api.GetBasicAuthGroup("/", zdpgo_api.StringMap{
		"zhangdapeng": "zhangdapeng",
	})

	// POST请求
	authorized.Get("/admin", func(c *zdpgo_api.Context) {
		user := c.MustGet(zdpgo_api.AuthUserKey).(string)
		c.JSON(http.StatusOK, zdpgo_api.JsonMap{"status": user})
	})

	return api
}

//go:embed uploads downloads
var fsObj embed.FS

func main() {
	r := setupRouter()

	// 添加静态目录
	r.AddStaticRouter("/static", "./uploads")
	r.AddStaticFSRouter("/fs", fsObj)

	// 监听地址 http://localhost:3333/ping?a=111&b=222#abc
	// 监听地址 http://localhost:3333/user/zhangdapeng
	// 监听地址 http://localhost:3333/static/test1.jpg
	// 监听地址 http://localhost:3333/fs/uploads/test1.jpg
	// 监听地址 http://localhost:3333/fs/downloads/test1.jpg
	// 监听地址 http://localhost:3333/admin
	r.Run()
}
基本权限校验
package main

import (
	"github.com/zhangdapeng520/zdpgo_api"
	"github.com/zhangdapeng520/zdpgo_api/gin"
)

// 用户列表
var secrets = gin.H{
	"zhangdapeng": gin.H{"email": "zhangdapeng@qq.com", "phone": "123433"},
}

func getSecrets(c *gin.Context) {
	// 获取用户名
	user := c.MustGet(gin.AuthUserKey).(string)

	// 取出数据
	if secret, ok := secrets[user]; ok {
		c.JSON(200, gin.H{"user": user, "secret": secret})
	} else {
		c.JSON(200, gin.H{"user": user, "secret": "No SECRET :("})
	}
}

func main() {
	api := zdpgo_api.NewWithConfig(zdpgo_api.Config{Debug: true})

	// 创建权限校验路由分组
	authorized := api.GetBasicAuthGroup("/admin", map[string]string{"zhangdapeng": "zhangdapeng"})

	// 校验接口
	authorized.GET("/secrets", getSecrets)

	// 启动服务。访问:http://localhost:3333/admin/secrets
	api.Run()
}
文件上传
package main

import (
	"github.com/zhangdapeng520/zdpgo_api"
)

func main() {
	api := zdpgo_api.NewWithConfig(zdpgo_api.Config{Debug: true})
	api.AddUploadRouter("/upload", "file", "uploads")
	api.Run()
}

Documentation

Index

Constants

View Source
const (
	AuthUserKey = "user" // 是基本身份验证中用户凭据的cookie名称。
)

Variables

View Source
var Log *zdpgo_log.Log // 日志对象

Functions

This section is empty.

Types

type Api added in v1.1.4

type Api struct {
	Config *Config        // 配置对象
	Log    *zdpgo_log.Log // 日志对象
	App    *gin.Engine    // 核心App对象
}

Api API核心对象

func New added in v1.1.4

func New() *Api

New 使用默认配置创建API

func NewWithConfig added in v1.1.4

func NewWithConfig(config Config) *Api

NewWithConfig 根据配置创建API

func (*Api) AddCorsMiddleware added in v1.1.4

func (a *Api) AddCorsMiddleware()

AddCorsMiddleware 添加跨域中间件

func (*Api) AddStaticFSRouter added in v1.1.6

func (a *Api) AddStaticFSRouter(routerPath string, fsObj fs.FS)

AddStaticFSRouter 添加嵌入式文件系统作为静态目录

func (*Api) AddStaticRouter added in v1.1.6

func (a *Api) AddStaticRouter(routerPath string, dirPath string)

AddStaticRouter 添加静态文件目录

func (*Api) AddUploadRouter added in v1.1.4

func (a *Api) AddUploadRouter(
	routerPath string,
	fileName string,
	saveDir string,
	handleResultList ...func(c *gin.Context, file *multipart.FileHeader, err error))

AddUploadRouter 添加文件上传路由 @param routerPath 路由路径,比如:/upload @param fileName 上传文件的表单名称,比如:file @param saveDir 文件的上传路径,比如:./uploads @param handleResultList 处理结果的方法列表,用户可以自定义文件上传后的返回内容,处理错误信息

func (*Api) Any added in v1.1.7

func (a *Api) Any(method, routerPath string, handleFuncList ...func(ctx *Context))

Any 处理任意方法类型

func (*Api) CreateDirs added in v1.1.4

func (a *Api) CreateDirs(filePath string) error

CreateDirs 调用os.MkdirAll递归创建文件夹

func (*Api) Delete added in v1.1.7

func (a *Api) Delete(routerPath string, handleFuncList ...func(ctx *Context))

Delete 处理DELETE方法类型

func (*Api) Get added in v1.1.7

func (a *Api) Get(routerPath string, handleFuncList ...func(ctx *Context))

Get 处理GET方法类型

func (*Api) GetBasicAuthGroup added in v1.1.4

func (a *Api) GetBasicAuthGroup(routerPath string, accounts StringMap) (group *ApiGroup)

GetBasicAuthGroup 获取基本权限校验路由组

func (*Api) InitValidator added in v1.1.4

func (a *Api) InitValidator() (err error)

InitValidator 初始化校验器

func (*Api) IsExists added in v1.1.4

func (a *Api) IsExists(path string) bool

IsExists 判断所给路径文件/文件夹是否存在(返回true是存在)

func (*Api) Patch added in v1.1.7

func (a *Api) Patch(routerPath string, handleFuncList ...func(ctx *Context))

Patch 处理PATCH方法类型

func (*Api) Post added in v1.1.7

func (a *Api) Post(routerPath string, handleFuncList ...func(ctx *Context))

Post 处理POST方法类型

func (*Api) Put added in v1.1.7

func (a *Api) Put(routerPath string, handleFuncList ...func(ctx *Context))

Put 处理PUT方法类型

func (*Api) Run added in v1.1.4

func (a *Api) Run(exitFuncList ...func())

Run 运行APP

func (*Api) SetApp added in v1.1.4

func (a *Api) SetApp(app *gin.Engine)

SetApp 设置APP

func (*Api) Validate added in v1.1.4

func (a *Api) Validate(data interface{}) (errData map[string]string)

Validate 校验结构体

type ApiGroup added in v1.1.7

type ApiGroup struct {
	gin.RouterGroup
}

ApiGroup API分组

func (*ApiGroup) Any added in v1.1.7

func (g *ApiGroup) Any(method, routerPath string, handleFuncList ...func(ctx *Context))

func (*ApiGroup) Delete added in v1.1.7

func (g *ApiGroup) Delete(routerPath string, handleFuncList ...func(ctx *Context))

Delete 处理DELETE方法类型

func (*ApiGroup) Get added in v1.1.7

func (g *ApiGroup) Get(routerPath string, handleFuncList ...func(ctx *Context))

Get 处理GET方法类型

func (*ApiGroup) Patch added in v1.1.7

func (g *ApiGroup) Patch(routerPath string, handleFuncList ...func(ctx *Context))

Patch 处理PATCH方法类型

func (*ApiGroup) Post added in v1.1.7

func (g *ApiGroup) Post(routerPath string, handleFuncList ...func(ctx *Context))

Post 处理POST方法类型

func (*ApiGroup) Put added in v1.1.7

func (g *ApiGroup) Put(routerPath string, handleFuncList ...func(ctx *Context))

Put 处理PUT方法类型

type Config added in v1.1.4

type Config struct {
	Debug          bool   `yaml:"debug" json:"debug"`                       // 是否为debug模式
	LogFilePath    string `yaml:"log_file_path" json:"log_file_path"`       // 日志路径
	Host           string `yaml:"host" json:"host"`                         // 启动地址,默认0.0.0.0
	Port           int    `yaml:"port" json:"port"`                         // 启动端口号,默认3333
	UploadFileSize int64  `yaml:"upload_file_size" json:"upload_file_size"` // 上传文件大小限制(M),默认33
}

type Context added in v1.1.7

type Context struct {
	gin.Context
}

Context 重命名gin上下文

type JsonMap added in v1.1.7

type JsonMap map[string]interface{}

JsonMap json字典类型

type StringMap added in v1.1.7

type StringMap map[string]string

StringMap 字符串类型的字典

Directories

Path Synopsis
core
examples
basic command
basic_auth command
file_upload command
grpc/api command
grpc/grpc command
grpc/pb
Package helloworld is a generated protocol buffer package.
Package helloworld is a generated protocol buffer package.
validator command
gin
Package api implements a HTTP web framework called api.
Package api implements a HTTP web framework called api.
Package validator implements value validations for structs and individual fields based on tags.
Package validator implements value validations for structs and individual fields based on tags.
Package yaml implements YAML support for the Go language.
Package yaml implements YAML support for the Go language.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL