goapi

package module
v0.1.9 Latest Latest
Warning

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

Go to latest
Published: Jan 10, 2025 License: MIT Imports: 28 Imported by: 0

README

goapi

使用OpenAPI3.1文档的HTTP框架

中文 | English

用法

go get github.com/goodluckxu-go/goapi

main.go

import (
	"github.com/fatih/color"
	"github.com/goodluckxu-go/goapi"
)

func main() {
	color.NoColor = true // 关闭默认日志控制台颜色
	api := goapi.GoAPI(true, "/docs")
	api.SetResponseMediaType(goapi.JSON)
	api.HTTPExceptionHandler(func(httpCode int, detail string) goapi.Response {
		return &goapi.HTTPResponse[Error]{
			HttpCode: httpCode, 
			Body: Error{
				Code:  httpCode, 
				Error: detail,
			},
		}
	})
	api.IncludeRouter(&IndexController{}, "/v1", true, func(ctx *goapi.Context) {
		ctx.Next()
	})
	_ = api.Run("127.0.0.1:8080")
}

user_controller.go

type UserController struct {
}

type UserListRouter struct {
}

type Req struct {
	JwtStr string `json:"jwt_str" desc:"json web token"`
	Page int `json:"page" desc:"now page" gt:"0"`
	Limit int `json:"page" desc:"limit a page count" gte:"10" lte:"100"`
}

func (u *UserListRouter) Index(input struct {
	router  goapi.Router `path:"/index/{id}" method:"put" summary:"test api" desc:"test api" tags:"admin"`
	Auth    *AdminAuth
	ID      string `path:"id" regexp:"^\d+$"` // path 
	Req     Req `body:"json"`
}) Resp {
	jwt := &goapi.JWT{
		Issuer: "custom", 
		Subject: input.Name,
		Audience: []string{"/v1"}, 
		ExpiresAt: time.Now().Add(5 * time.Minute), 
		NotBefore: time.Now(), 
		IssuedAt: time.Now(), 
		ID: "uuid",
		Extensions: map[string]any{
			"name":     1, 
			"age":      15, 
			"zhangsan": "user",
		},
	}
	jwtStr, err := jwt.Encrypt(&AuthToken{})
	if err != nil {
		response.HTTPException(-1, err.Error())
	}
	return Resp{
		JwtStr: jwtStr
	}
}

// 实现HTTPBearer接口
type AdminAuth struct {
	Admin  string          // 定义一个值并从控制器检索它
}

func (h *AdminAuth) HTTPBearer(token string) {
	if token != "123456" {
		response.HTTPException(401, "token is error")   
	}
	h.Admin = "admin"
}

// 实现HTTPBearerJWT接口
type AuthToken struct {
	Name string // 定义一个值并从控制器检索它
}

var privateKey, _ = os.ReadFile("private.pem")
var publicKey, _ = os.ReadFile("public.pem")

func (a *AuthToken) EncryptKey() (any, error) {
	block, _ := pem.Decode(privateKey)
	return x509.ParsePKCS8PrivateKey(block.Bytes)
}

func (a *AuthToken) DecryptKey() (any, error) {
	block, _ := pem.Decode(publicKey)
	return x509.ParsePKIXPublicKey(block.Bytes)
}

func (a *AuthToken) SigningMethod() goapi.SigningMethod {
	return goapi.SigningMethodRS256
}

func (a *AuthToken) HTTPBearerJWT(jwt *goapi.JWT) {
	fmt.Println(jwt)
	a.Name = jwt.Subject
}

// 实现HTTPBasic接口
type AdminAuth struct {
	Admin  string          // 定义一个值并从控制器检索它
}

func (h *AdminAuth) HTTPBasic(username,password string) {
	if username != "admin" || password != "123456" {
		response.HTTPException(401, "token is error")
	} 
	h.Admin = "admin"
}


// 实现ApiKey接口
type AdminAuth struct {
	Token  string   `header:"Token"`
	Admin  string          // 定义一个值并从控制器检索它
}

func (h *AdminAuth) ApiKey() {
	if h.Token != "123456" {
		response.HTTPException(401, "token is error")
	}
	h.Admin = "admin"
}

验证的多语言设置

可以自己实现'goapi.Lang'接口

api.SetLang(&lang.ZhCn{}) // 默认EnUs英文注释

日志输出设置

在初始化api之前设置

goapi.SetLogLevel(goapi.LogInfo | goapi.LogWarning)
'goapi.Router'标记字段注释
  • path: 路由地址
  • method: 访问方法。多个内容用','分隔
  • summary: 该API的简短摘要。
  • desc: API的描述。CommonMark语法可用于富文本表示。
  • tags: 多个内容用','分隔
方法中参数结构标签的标注
  • header
    • 可以使用常用类型(ptr, slice),在切片类型中使用','拆分
    • 值是字段的别名,添加'omitempty'则可为空
  • cookie
    • 可以使用常用的类型(ptr, slice)或`*http.Cookie',在切片类型中使用','拆分
    • 值是字段的别名,添加'omitempty'则可为空
  • query
    • 可以使用常用类型(ptr, slice)
    • 值是字段的别名,添加'omitempty'则可为空
  • path
    • 可以使用常用类型(ptr, slice),在切片类型中使用','拆分
    • 值是字段的别名,添加'omitempty'则可为空
  • form
    • 可以使用常用类型(ptr, slice),在切片类型中使用','拆分
    • 默认媒体类型'application/x-www-form-urlencoded',如果有file文件存在媒体类型为'multipart/form-data'
    • 值是字段的别名,添加'omitempty'则可为空
  • file
    • 可以使用类型为‘*multipart.FileHeader'或'[]*multipart.FileHeader'
    • 默认媒体类型“multipart/form-data”
    • 值是字段的别名,添加'omitempty'则可为空
  • body
    • 固定常用值为'xml'和'json', 多个值用','分割
    • 该值适用于其他媒体类型(例如'text/plain'),值类型为'[]byte', 'string'或'io.ReadCloser'
    • 值json表示媒体类型'application/json', 值xml表示媒体类型'application/xml'
    • 标签使用值的主体, 添加'omitempty'则可为空
    • 值为'application/octet-stream'时,表示body以文件的方式上传
结构标签注释
  • regexp
    • 值的正则表达式
    • 验证器限制 字符串 类型
    • 相当于OpenAPI的 pattern
  • enum
    • 值的枚举
    • 验证器限制 整数 数字 布尔 字符串 类型
    • 逗号分割(,)
  • default
    • 默认值
  • example
    • 实例值
  • desc
    • 字段描述
    • 相当于OpenAPI的 description
  • lt
    • 小于字段值
    • 验证器限制 整数 数字 类型
    • 相当于OpenAPI的 exclusiveMaximum
  • lte
    • 小于等于字段值
    • 验证器限制 整数 数字 类型
    • 相当于OpenAPI的 maximum
  • gt
    • 大于字段值
    • 验证器限制 整数 数字 类型
    • 相当于OpenAPI的 exclusiveMinimum
  • gte
    • 大于等于字段值
    • 验证器限制 整数 数字 类型
    • 相当于OpenAPI的 minimum
  • multiple
    • 值的乘数
    • 验证器限制 整数 数字 类型
  • max
    • 值的最大长度
    • 验证器限制 字符串 数组 对象 类型
  • min
    • 值的最小长度
    • 验证器限制 字符串 数组 对象 类型
  • unique
    • 验证数组值唯一
    • 验证器限制 数组 类型

响应注释

如果响应是goapi的实现。响应界面,可以设置一些功能
  • HTTPResponse[T] 可以设置http的code,header,cookie,Content-Type值为'application/json','application/xml'
  • FileResponse 可以返回可下载文件,Content-Type值为'application/octet-stream'
  • SSEResponse 可以以服务器发送事件格式返回内容,Content-Type值为'text/event-stream'
  • HTMLResponse 可以返回HTML页面,Content-Type值为'text/html'
  • TextResponse 文本方式的返回,可以设置header, cookie,Content-Type默认值为'text/plain',可重置Content-Type

错误对应注释以及用法

response.HTTPException(404, "error message")
  • 具体的返回信息可以使用'HTTPExceptionHandler'方法配置
  • 第一个参数是HTTP状态码,第二个是错误消息,第三个是返回的报头设置

关于

使用类似于Python中的FastAPI的API生成文档

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// hmac
	SigningMethodHS256 *SigningMethodHMAC = jwt.SigningMethodHS256
	SigningMethodHS384 *SigningMethodHMAC = jwt.SigningMethodHS384
	SigningMethodHS512 *SigningMethodHMAC = jwt.SigningMethodHS512
	// rsa
	SigningMethodRS256 *SigningMethodRSA = jwt.SigningMethodRS256
	SigningMethodRS384 *SigningMethodRSA = jwt.SigningMethodRS384
	SigningMethodRS512 *SigningMethodRSA = jwt.SigningMethodRS512
	// ecdsa
	SigningMethodES256 *SigningMethodECDSA = jwt.SigningMethodES256
	SigningMethodES384 *SigningMethodECDSA = jwt.SigningMethodES384
	SigningMethodES512 *SigningMethodECDSA = jwt.SigningMethodES512
	// ed25519
	SigningMethodEdDSA *SigningMethodEd25519 = jwt.SigningMethodEdDSA
)

Functions

func ParseCommentXml added in v0.1.9

func ParseCommentXml(v any) (rs string)

func SetLogLevel added in v0.0.2

func SetLogLevel(level LogLevel)

Types

type API

type API struct {
	OpenAPIInfo *openapi.Info

	OpenAPIServers []*openapi.Server
	OpenAPITags    []*openapi.Tag
	Swagger        swagger.Config
	// contains filtered or unexported fields
}

func GoAPI

func GoAPI(isDocs bool, docsPath ...string) *API

GoAPI It is a newly created API function

func (*API) AddMiddleware

func (a *API) AddMiddleware(middlewares ...Middleware)

AddMiddleware It is a function for adding middleware

func (*API) DebugPprof added in v0.0.4

func (a *API) DebugPprof()

DebugPprof Open the system's built-in pprof

func (*API) HTTPExceptionHandler

func (a *API) HTTPExceptionHandler(f func(httpCode int, detail string) Response)

HTTPExceptionHandler It is an exception handling registration for HTTP

func (*API) Handler added in v0.0.9

func (a *API) Handler() http.Handler

Handler Return to http.Handler interface

func (*API) IncludeChildAPI added in v0.1.2

func (a *API) IncludeChildAPI(child *ChildAPI)

IncludeChildAPI It is an introduction routing children

func (*API) IncludeGroup added in v0.0.6

func (a *API) IncludeGroup(group *APIGroup)

IncludeGroup It is an introduction routing group

func (*API) IncludeRouter

func (a *API) IncludeRouter(router any, prefix string, isDocs bool, middlewares ...Middleware)

IncludeRouter It is a function that introduces routing structures

func (*API) Logger added in v0.0.7

func (a *API) Logger() Logger

Logger It is a method of obtaining logs

func (*API) Run

func (a *API) Run(addr ...string) (err error)

Run attaches the router to a http.Server and starts listening and serving HTTP requests. It is a shortcut for http.ListenAndServe(addr, router) Note: this method will block the calling goroutine indefinitely unless an error happens.

func (*API) RunTLS added in v0.0.9

func (a *API) RunTLS(addr, certFile, keyFile string) (err error)

RunTLS attaches the router to a http.Server and starts listening and serving HTTPS (secure) requests. It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router) Note: this method will block the calling goroutine indefinitely unless an error happens.

func (*API) SetLang

func (a *API) SetLang(lang Lang)

SetLang It is to set the validation language function

func (*API) SetLogger added in v0.0.2

func (a *API) SetLogger(log Logger)

SetLogger It is a function for setting custom logs

func (*API) SetResponseMediaType

func (a *API) SetResponseMediaType(mediaTypes ...MediaType)

SetResponseMediaType It is a function that sets the return value type

func (*API) SetStructTagVariableMapping added in v0.1.5

func (a *API) SetStructTagVariableMapping(m map[string]string)

SetStructTagVariableMapping It is set struct tag variable mapping Only supports the replacement of tags 'summary' and 'desc' example:

mapping:
	username: test
	password: 123456
tag value:
	username is {{username}} and password is {{password}}
result value:
	username is test and password is 123456

func (*API) Static added in v0.0.4

func (a *API) Static(path, root string)

Static serves files from the given file system root.

type APIGroup added in v0.0.6

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

func NewGroup added in v0.0.6

func NewGroup(prefix string, isDocs bool) *APIGroup

NewGroup It is a newly created APIGroup function

func (*APIGroup) AddMiddleware added in v0.0.6

func (g *APIGroup) AddMiddleware(middlewares ...Middleware)

AddMiddleware It is a function for adding middleware

func (*APIGroup) IncludeGroup added in v0.0.6

func (g *APIGroup) IncludeGroup(group *APIGroup)

IncludeGroup It is an introduction routing group

func (*APIGroup) IncludeRouter added in v0.0.6

func (g *APIGroup) IncludeRouter(router any, prefix string, isDocs bool, middlewares ...Middleware)

IncludeRouter It is a function that introduces routing structures

type ApiKey

type ApiKey interface {
	ApiKey()
}

ApiKey verification interface

type ChildAPI added in v0.1.2

type ChildAPI struct {
	OpenAPIInfo    *openapi.Info
	OpenAPIServers []*openapi.Server
	OpenAPITags    []*openapi.Tag
	// contains filtered or unexported fields
}

func NewChildAPI added in v0.1.2

func NewChildAPI(prefix string, isDocs bool, docsPath string) *ChildAPI

NewChildAPI It is a newly created ChildAPI function

func (*ChildAPI) AddMiddleware added in v0.1.2

func (c *ChildAPI) AddMiddleware(middlewares ...Middleware)

AddMiddleware It is a function for adding middleware

func (*ChildAPI) IncludeGroup added in v0.1.2

func (c *ChildAPI) IncludeGroup(group *APIGroup)

IncludeGroup It is an introduction routing group

func (*ChildAPI) IncludeRouter added in v0.1.2

func (c *ChildAPI) IncludeRouter(router any, prefix string, isDocs bool, middlewares ...Middleware)

IncludeRouter It is a function that introduces routing structures

type Context

type Context struct {
	Request *http.Request
	Writer  http.ResponseWriter

	Values map[string]any
	// contains filtered or unexported fields
}

func (*Context) ClientIP added in v0.0.12

func (c *Context) ClientIP() string

ClientIP implements one best effort algorithm to return the real client IP. It is it will then try to parse the headers defined in http.Header (defaulting to [X-Forwarded-For, X-Real-Ip]). else the remote IP (coming from Request.RemoteAddr) is returned.

func (*Context) Deadline

func (c *Context) Deadline() (deadline time.Time, ok bool)

func (*Context) Done

func (c *Context) Done() <-chan struct{}

func (*Context) Err

func (c *Context) Err() error

func (*Context) FullPath added in v0.0.11

func (c *Context) FullPath() string

FullPath returns a matched route full path. For not found routes returns an empty string.

func (*Context) Get

func (c *Context) Get(key string) (value any, ok bool)

Get It is a method for obtaining context values

func (*Context) Logger added in v0.0.3

func (c *Context) Logger() Logger

Logger It is a method of obtaining logs

func (*Context) Next

func (c *Context) Next()

Next It is used in middleware, before Next is before interface request, and after Next is after interface request

func (*Context) RemoteIP added in v0.0.12

func (c *Context) RemoteIP() string

RemoteIP parses the IP from Request.RemoteAddr, normalizes and returns the IP (without the port).

func (*Context) Set

func (c *Context) Set(key string, value any)

Set It is a method for setting context values

func (*Context) Value

func (c *Context) Value(key any) any

type HTTPBasic

type HTTPBasic interface {
	HTTPBasic(username, password string)
}

HTTPBasic verification interface

type HTTPBearer

type HTTPBearer interface {
	HTTPBearer(token string)
}

HTTPBearer verification interface

type HTTPBearerJWT added in v0.1.2

type HTTPBearerJWT interface {
	// EncryptKey the encrypted key
	EncryptKey() (any, error)

	// DecryptKey the Decryption key
	DecryptKey() (any, error)

	// SigningMethod encryption and decryption methods
	SigningMethod() SigningMethod

	// HTTPBearerJWT jwt logical
	HTTPBearerJWT(jwt *JWT)
}

HTTPBearerJWT verification interface

type JWT added in v0.1.2

type JWT struct {
	// the `iss` (Issuer) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.1
	Issuer string `json:"iss"`

	// the `sub` (Subject) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.2
	Subject string `json:"sub"`

	// the `aud` (Audience) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3
	Audience []string `json:"aud"`

	// the `exp` (Expiration Time) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.4
	ExpiresAt time.Time `json:"exp"`

	// the `nbf` (Not Before) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.5
	NotBefore time.Time `json:"nbf"`

	// the `iat` (Issued At) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.6
	IssuedAt time.Time `json:"iat"`

	// the `jti` (JWT ID) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.7
	ID string `json:"jti"`

	Extensions map[string]any `json:"ext"`
}

func (*JWT) Encrypt added in v0.1.2

func (j *JWT) Encrypt(bearerJWT HTTPBearerJWT) (string, error)

Encrypt Get Jwt encrypted string

func (*JWT) GetAudience added in v0.1.2

func (j *JWT) GetAudience() (jwt.ClaimStrings, error)

func (*JWT) GetExpirationTime added in v0.1.2

func (j *JWT) GetExpirationTime() (*jwt.NumericDate, error)

func (*JWT) GetIssuedAt added in v0.1.2

func (j *JWT) GetIssuedAt() (*jwt.NumericDate, error)

func (*JWT) GetIssuer added in v0.1.2

func (j *JWT) GetIssuer() (string, error)

func (*JWT) GetNotBefore added in v0.1.2

func (j *JWT) GetNotBefore() (*jwt.NumericDate, error)

func (*JWT) GetSubject added in v0.1.2

func (j *JWT) GetSubject() (string, error)

func (*JWT) MarshalJSON added in v0.1.2

func (j *JWT) MarshalJSON() ([]byte, error)

type Lang

type Lang interface {
	Required(field string) string
	Lt(field string, val float64) string
	Lte(field string, val float64) string
	Gt(field string, val float64) string
	Gte(field string, val float64) string
	MultipleOf(field string, val float64) string
	Max(field string, val uint64) string
	Min(field string, val uint64) string
	Unique(field string) string
	Regexp(field string, val string) string
	Enum(field string, val []any) string
	JwtTranslate(msg string) string
}

type LogLevel added in v0.0.2

type LogLevel uint
const (
	LogInfo LogLevel = 1 << iota
	LogDebug
	LogWarning
	LogError
	LogFail
)

type Logger added in v0.0.2

type Logger interface {
	Debug(format string, a ...any)
	Info(format string, a ...any)
	Warning(format string, a ...any)
	Error(format string, a ...any)
	Fatal(format string, a ...any)
}

type MediaType

type MediaType string
const JSON MediaType = "application/json"
const XML MediaType = "application/xml"

type Middleware

type Middleware func(ctx *Context)

type Response

type Response interface {
	GetBody() any
	GetContentType() string
	SetContentType(contentType string)
	Write(w http.ResponseWriter)
}

type ResponseWriter added in v0.0.2

type ResponseWriter struct {
	http.ResponseWriter
	// contains filtered or unexported fields
}

func (*ResponseWriter) Flush added in v0.0.3

func (r *ResponseWriter) Flush()

Flush implements the http.Flusher interface.

func (*ResponseWriter) Header added in v0.0.2

func (r *ResponseWriter) Header() http.Header

func (*ResponseWriter) Hijack added in v0.0.3

func (r *ResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)

Hijack implements the http.Hijacker interface.

func (*ResponseWriter) Status added in v0.0.2

func (r *ResponseWriter) Status() int

func (*ResponseWriter) Write added in v0.0.2

func (r *ResponseWriter) Write(b []byte) (int, error)

func (*ResponseWriter) WriteHeader added in v0.0.2

func (r *ResponseWriter) WriteHeader(statusCode int)

type Router

type Router struct{}

Router is used to set access routes and routing methods

Tag Description:
	path: Access Routing
	method: Access method. Multiple contents separated by ','
	summary: A short summary of the API.
	desc: A description of the API. CommonMark syntax MAY be used for rich text representation.
	tags: Multiple contents separated by ','

type SecurityDescription added in v0.1.8

type SecurityDescription interface {
	Desc() string
}

type SigningMethod added in v0.1.2

type SigningMethod = jwt.SigningMethod

type SigningMethodECDSA added in v0.1.2

type SigningMethodECDSA = jwt.SigningMethodECDSA

type SigningMethodEd25519 added in v0.1.2

type SigningMethodEd25519 = jwt.SigningMethodEd25519

type SigningMethodHMAC added in v0.1.2

type SigningMethodHMAC = jwt.SigningMethodHMAC

type SigningMethodRSA added in v0.1.2

type SigningMethodRSA = jwt.SigningMethodRSA

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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