kapi

package module
v0.5.6 Latest Latest
Warning

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

Go to latest
Published: Jan 5, 2023 License: MIT Imports: 31 Imported by: 1

README

kapi

PS

目前正在从gitee转移到github...., 慢慢更新中

介绍

基于gin的扩展, 支持 //@POST 式注释路由, 解析结构体并生成swagger文档

注意: 还有很多问题, 不要在生产环境使用, 会很难受的

特性

  1. 使用注释路由
  2. 更简单的swagger文档生成方式

注意

由于使用了go 1.16新增的embed特性, 因此只能在1.16以上版本使用

快速开始

  1. https://github.com/linxlib/k 安装cli
  2. 安装后执行go mod init {module_name} 然后 k init, 自动创建 config.toml build.toml main.go 等
    k := kapi.New(func(option *kapi.Option) {
	   
    })
    // 注册路由
    k.RegisterRouter(new(controller.BannerController),
        new(controller.AssetController),
        new(controller.CategoryController),
        new(controller.UserController),
        new(controller.SysConfigController))
	k.Run() //运行
  1. 创建 controller.HelloController , 并实现一个路由方法
//HelloController <here will be tag name>
//@TAG <here will be tag name>
//@AUTH Authorization
//@ROUTE /api
type HelloController struct {
	BaseAuthController
}

type PageSize struct {
	Page int `query:"page,default=1" binding:"required"`
	Size int `query:"size,default=15"`
}

func (ps *PageSize) GetLimit() (int,int) {
	return ps.Size,(ps.Page-1)*ps.Size
}

type HelloWorld1Req struct {
	PageSize
	Name string `query:"name" binding:"required"`
	Authorization string `header:"Authorization"`
	File *multipart.FileHeader
	
}
// World1 World1
// @GET /hello/list
func (h *HelloController) World1(c *kapi.Context,req *HelloWorld1Req) {
	c.SuccessExit()
}

其他路由和swagger文档相关请到example中查看

  1. 运行 go run main.go 或者 k run

具体用法可查看example文件夹 不断更新中

支持一些奇怪的特性 🐶

  • //@TAG 分类 在struct上增加, 可以指定在swagger文档中的标签, 默认为struct的名字, 目前不加@TAG注释, 则默认使用struct自己的注释
  • 一个方法List上如果有这样的注释 //List 获取列表 那么获取列表 将作为一个路由的Summary显示在swagger文档里
  • //@AUTH Authorization 在struct上增加, 可以为该struct的每个方法的请求参数加上一个Header请求头, 其中 Authorization 可以不要, 默认是 Authorization. 这个需要配合 BaseAuthController来对各个方法进行鉴权
  • //@ROUTE /banner 为该struct下的方法增加一个路由地址的前缀, 会拼接起来. 例如 struct上有//@ROUTE /banner, 其下方的方法//@GET /list 则实际的路由为 GET /banner/list
  • 请求的参数可以使用类似继承的方式来声明参数.
type PageSize struct {
    Page int `query:"page,default=1"`
    Size int `query:"size,default=15"`
}

func (p *PageSize) GetLimit() (int, int) {
    return p.Size, (p.Page - 1) * p.Size
}
type GetBannerListReq struct {
	PageSize
}
  • 请求参数的struct支持多种tag, query path header json defaultbinding, 这个是基于gin的bind实现的, 由于不同类型的参数混在一起, 因此这里可能需要优化性能

  • kapi.Context包含一些Exit方法, 可以不用return直接跳出流程, 这是通过panic实现的, 当然如果方法使用了返回值, 就不能用这个方式了

  • 实现了 kapi.Interceptor 的中间件, 可以存储一些上下文数据, 比如 当前用户 CurrentUser *model.User, 无需使用Context的相关方法

  • kapi.RegisterFuncGetResult 可以修改默认的返回json的结构, 为自带的 *Exit系方法自定义返回

  • since v0.3.2 //@RESP model.User 可以注明方法返回结构体,用于没有返回值的方法在文档中显示返回类型

  • since v0.3.2 可以在方法上指定多个HTTP METHOD 例如可以写多行 @GET @POST @PUT, 不过请求路径会以最后一个为准

部署

k build./bin/版本/系统_架构/目录下的文件即为全部, 如果是自行编译, 则需要同时拷贝swagger.json和gen.gob以及config.toml.

当前主分支, 在 k build -g 后会覆盖 swagger.jsongen.gob ,config.toml则仅当输出目录下不存在config.toml时才会拷贝

TODO

  • 修改为func方式配置kapi
  • controller 增加 //@ROUTE 用于标记整个controller的path
  • 增加@AUTH标记支持, 用于设置传输token的header名, 可以放在controller上
  • 增加静态目录配置, Context增加 SaveFile
  • 在issue中进行任务处理
  • 加入二维数组支持
  • 请求参数可以使用类似继承的方式来重用结构
  • 配置文件配置服务 (需要配合 k init)
  • 增加命令行参数用于仅生成路由和文档, 实现编译前无需运行即可更新文档
  • 优化ast包解析, 减少循环 (目前通过增加map来缓存需要的数据, 重复的对象不会多次遍历ast树)
  • k cli 加入项目判断, 使其可用于其他纯go项目的编译
  • 重构ast解析部分,提升效率
  • 新的参数默认值,废弃旧的 default tag,改为使用gin的 query:"name,default=hello"
  • RapiDoc
  • 增加一个注解用于注释返回结构类型, 特指只有一个Context的方法 @RESP
  • 增加multipart.FileHeader的支持
  • 部分功能提取为单独包
  • k编译打包时增加进度显示, 优化打包速度
  • 精简引用包,减小体积
  • 加入markdown形式的文档
  • 拦截器实现多个顺序执行机制(栈)
  • 加入枚举支持

感谢

https://github.com/xxjwxc/ginrpc 大部分代码参考该项目, 例如代码解析\文档生成, 由于我需要一个方便单纯写写接口, 快速生成文档, 该项目无法满足, 而且也很难在基础上进行PR(改动较大, 并可能无法适应比较大众化的框架需求), 才有了魔改一顿的想法

k

介绍

这是本框架提供的命令行工具, 代码基本来自 github.com/gogf/gf-cli, 目前包含 安装、运行、编译三个部分, 后续会加入其它功能.

使用kapi进行开发, 建议同时使用k-cli, 由于kapi的swagger文档以及路由注册需要在开发环境运行后才会生成, 使用go自带的编译可能无法正常使用文档和注册路由

目前移动到 https://github.com/linxlib/k 仓库

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	VERSION     string
	BUILDTIME   string
	GOVERSION   string
	OS          string
	ARCH        string
	PACKAGENAME string
)

编译时植入变量

View Source
var GetResultFunc = _defaultGetResult
View Source
var KAPIEXIT = "kapiexit"

Functions

func RegisterFuncGetResult added in v0.3.0

func RegisterFuncGetResult(i FuncGetResult)

RegisterFuncGetResult 注册返回json结构的func

Types

type AfterBind

type AfterBind interface {
	AfterBind(c *Context)
}

type AfterCall

type AfterCall interface {
	AfterCall(c *Context)
}

type BeforeBind

type BeforeBind interface {
	BeforeBind(c *Context)
}

type BeforeCall

type BeforeCall interface {
	BeforeCall(c *Context)
}

type Context

type Context struct {
	*gin.Context
	// contains filtered or unexported fields
}

Context KApi Context

func (*Context) Apply

func (c *Context) Apply(ctl interface{}) error

Apply 为一个结构注入带inject标签的Field

@param ctl 需要为指针

@return error

func (*Context) DataExit

func (c *Context) DataExit(data interface{})

func (*Context) Exit

func (c *Context) Exit()

func (*Context) FailAndExit

func (c *Context) FailAndExit(data ...interface{})

func (*Context) GetFormFloat32

func (c *Context) GetFormFloat32(key string, def ...float32) float32

GetFormFloat32 return the float32 value of query param

@param key
@param def

@return string

func (*Context) GetFormFloat64

func (c *Context) GetFormFloat64(key string, def ...float64) float64

GetFormFloat64 return the float64 value of form param

@param key
@param def

@return string

func (*Context) GetFormInt

func (c *Context) GetFormInt(key string, def ...int) int

GetFormInt return the int value of form param

@param key

@return string

func (*Context) GetFormInt64

func (c *Context) GetFormInt64(key string, def ...int64) int64

GetFormInt64 return the int64 value of form param

@param key

@return string

func (*Context) GetFormString

func (c *Context) GetFormString(key string, def ...string) string

GetFormString return the string value of form param

@param key

@return string

func (*Context) GetFormUInt

func (c *Context) GetFormUInt(key string, def ...uint) uint

GetFormUInt return the uint value of form param

@param key

@return string

func (*Context) GetPageSize

func (c *Context) GetPageSize(def ...int) (int, int)

GetPageSize return the values of "page"-1 and "size" query params

@param def
def[0] can be the default value of "page" param and def[1] can be the default value of "size" param

@return int page-1
@return int size

func (*Context) GetQueryBool

func (c *Context) GetQueryBool(key string) bool

GetQueryBool return the boolean value of query param

@param key

@return bool

func (*Context) GetQueryInt

func (c *Context) GetQueryInt(key string, def ...int) int

GetQueryInt return the int value of query param

@param key
@param def

@return int

func (*Context) GetQueryInt64

func (c *Context) GetQueryInt64(key string, def ...int64) int64

GetQueryInt64 return the int64 value of query param

@param key
@param def

@return int64

func (*Context) GetQueryString

func (c *Context) GetQueryString(key string, def ...string) string

GetQueryString return the string value of query param

@param key

@return string

func (*Context) GetQueryUInt

func (c *Context) GetQueryUInt(key string, def ...uint) uint

GetQueryUInt return the uint value of query param

@param key
@param def

@return uint

func (*Context) GetQueryUInt64

func (c *Context) GetQueryUInt64(key string, def ...uint64) uint64

GetQueryUInt64 return the uint64 value of query param

@param key
@param def

@return uint64

func (*Context) ListExit

func (c *Context) ListExit(count int64, list interface{})

func (*Context) Map

func (c *Context) Map(i ...interface{}) inject.TypeMapper

Map an instance

@param i

@return inject.TypeMapper

func (*Context) MapTo

func (c *Context) MapTo(i interface{}, j interface{}) inject.TypeMapper

MapTo map instance to interface

@param i 要注入的值(指针)
@param j 接口类型(指针)

@return inject.TypeMapper

func (*Context) MessageAndDataExit

func (c *Context) MessageAndDataExit(message string, data interface{})

func (*Context) Method

func (c *Context) Method() string

Method return HTTP method

@return string

func (*Context) NoPerm

func (c *Context) NoPerm(msg ...string)

func (*Context) NoPermissionExit

func (c *Context) NoPermissionExit(msg ...string)

func (*Context) NotFoundExit

func (c *Context) NotFoundExit(msg ...string)

func (*Context) OfFormFile

func (c *Context) OfFormFile(form string) (string, int64)

OfFormFile 获取Form File的文件名和大小

@param form

@return string
@return int64

func (*Context) Provide

func (c *Context) Provide(i interface{}) error

Provide 提供已注入的实例

@param i 需要为指针

@return error

func (*Context) RemoteAddr

func (c *Context) RemoteAddr() string

RemoteAddr returns more real IP address.

func (*Context) SaveFile

func (c *Context) SaveFile(form string, dst string) error

SaveFile save form file to destination

@param form name of form file
@param dst destination file name

@return error

func (*Context) Success

func (c *Context) Success(data ...interface{})

func (*Context) SuccessExit

func (c *Context) SuccessExit(data ...interface{})

func (*Context) UnAuthed

func (c *Context) UnAuthed(msg ...string)

func (*Context) WriteJSON

func (c *Context) WriteJSON(obj interface{})

WriteJSON 写入json对象

type ContextInvoker

type ContextInvoker func(ctx *Context)

ContextInvoker method like this will be FastInvoke by inject package(not use reflect)

func (ContextInvoker) Invoke

func (invoke ContextInvoker) Invoke(params []interface{}) ([]reflect.Value, error)

type FuncGetResult added in v0.3.0

type FuncGetResult = func(code RESULT_CODE, msg string, count int64, data interface{}) (int, interface{})

type HeaderAuth

type HeaderAuth interface {
	HeaderAuth(c *Context)
}

type Interceptor

type Interceptor interface {
	Before(*Context)
	After(*Context)
}

Interceptor implement this to intercept controller method

type KApi

type KApi struct {
	inject.Injector
	// contains filtered or unexported fields
}

func New

func New(f ...func(*Option)) *KApi

func (*KApi) GetEngine

func (b *KApi) GetEngine() *gin.Engine

func (*KApi) RegisterRouter

func (b *KApi) RegisterRouter(cList ...interface{})

func (*KApi) Run

func (b *KApi) Run()

type MethodComment

type MethodComment struct {
	Key          string //may be [controller name] + / + [method name]. unique
	RouterPath   string
	IsDeprecated bool   // will show deprecated in swagger ui
	ResultType   string //then response type name. eg. model.User or []model.User
	Summary      string
	Description  string
	Method       string //HTTP METHOD
	TokenHeader  string
}

MethodComment store the comment from controller's method. fields should be exported for gob encoding and decoding

type OnError

type OnError interface {
	OnError(c *Context, err error)
}

type OnPanic

type OnPanic interface {
	OnPanic(c *Context, err interface{})
}

type OnUnmarshalError

type OnUnmarshalError interface {
	OnUnmarshalError(c *Context, err error)
}

type OnValidationError

type OnValidationError interface {
	OnValidationError(c *Context, err error)
}

type Option

type Option struct {
	Server Server `conf:"server"`
	// contains filtered or unexported fields
}

func (*Option) SetGinLoggerFormatter

func (o *Option) SetGinLoggerFormatter(formatter gin.LogFormatter) *Option

func (*Option) SetIntranetIP

func (o *Option) SetIntranetIP(ip string) *Option

func (*Option) SetRecoverFunc

func (o *Option) SetRecoverFunc(f func(interface{})) *Option

type RESULT_CODE added in v0.3.0

type RESULT_CODE int
const (
	RESULT_CODE_SUCCESS RESULT_CODE = iota //SuccessExit DataExit ListExit 时
	RESULT_CODE_FAIL                       // FailExit
	RESULT_CODE_ERROR                      //FailExit时传参error
	RESULT_CODE_UNAUTHED
	RESULT_CODE_NOPERMISSION
	RESULT_CODE_NOTFOUND
)

type RecoverErrorFunc

type RecoverErrorFunc func(interface{})

RecoverErrorFunc recover 错误设置

type RouteInfo

type RouteInfo struct {
	// contains filtered or unexported fields
}

func (*RouteInfo) AddFunc

func (ri *RouteInfo) AddFunc(handlerFuncName, routerPath string, method string)

AddFunc add one method to method comments

func (*RouteInfo) SetApiBody

func (ri *RouteInfo) SetApiBody(api swagger.APIBody)

SetApiBody store swagger json spec

@param api

type Server added in v0.5.4

type Server struct {
	Debug                       bool     `conf:"debug"`
	NeedDoc                     bool     `conf:"needDoc"`
	DocName                     string   `conf:"docName" default:"K-Api"`
	DocDesc                     string   `conf:"docDesc" default:"K-Api"`
	Port                        int      `conf:"port" default:"2022"`
	DocVer                      string   `conf:"docVer" default:"v1"`
	RedirectToDocWhenAccessRoot bool     `conf:"redirectToDocWhenAccessRoot"`
	StaticDirs                  []string `conf:"staticDirs" default:"[static=static]"`
	EnablePProf                 bool     `conf:"enablePProf"`
	Cors                        struct {
		AllowAllOrigins     bool          `conf:"allowAllOrigins"`
		AllowCredentials    bool          `conf:"allowCredentials"`
		MaxAge              time.Duration `conf:"maxAge"`
		AllowWebSockets     bool          `conf:"allowWebSockets"`
		AllowWildcard       bool          `conf:"allowWildcard"`
		AllowPrivateNetwork bool          `conf:"allowPrivateNetwork"`
		AllowMethods        []string      `conf:"allowMethods" d`
		AllowHeaders        []string      `conf:"allowHeaders"`
	} `conf:"cors"`
}

Directories

Path Synopsis
cmd
k command
example module
Package inject provides utilities for mapping and injecting dependencies in various ways.
Package inject provides utilities for mapping and injecting dependencies in various ways.
doc

Jump to

Keyboard shortcuts

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