goapi

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Jun 27, 2024 License: MIT Imports: 20 Imported by: 0

README

goapi

About the OpenAPI3.1.0 usage of http

usage

go get github.com/goodluckxu-go/goapi

main.go入口文件

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

func main() {
	api := goapi.GoAPI(&app.Gin{}, 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 {
}

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"` // path 
	Req     Req `body:"json"`
}) Resp {
	return Resp{}
}

// Implement HTTPBearer interface
type AdminAuth struct {
	Admin  string          // Define a value and retrieve it from the controller
}

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

// Implement HTTPBasic interface
type AdminAuth struct {
	Admin  string          // Define a value and retrieve it from the controller
}

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

// Auth verification
type UserListHeader struct { 
	Token     string
	param.Header     // inherit
}

// Implement ApiKey interface
type AdminAuth struct {
	Header *UserListHeader
	Admin  string          // Define a value and retrieve it from the controller
}

func (h *AdminAuth) ApiKey() {
	if h.Header.token != "123456" {
		response.HTTPException(401, "token is error")
	}
	h.Admin = "admin"
}
Structure tag field annotation
  • header
    • Can use commonly used types(ptr, slice), in slice type use ',' split
    • Value is an alias for a field, 'omitempty' is nullable
  • cookie
    • Can use commonly used types(ptr, slice) or *http.Cookie, in slice type use ',' split
    • Value is an alias for a field, 'omitempty' is nullable
  • query
    • Can use commonly used types(ptr, slice)
    • Value is an alias for a field, 'omitempty' is nullable
  • path
    • Can use commonly used types(ptr, slice), in slice type use ',' split
    • Value is an alias for a field, 'omitempty' is nullable
  • form
    • Can use commonly used types(ptr, slice), in slice type use ',' split
    • default media type 'application/x-www-form-urlencoded', if file exists 'multipart/form-data'
    • Value is an alias for a field, 'omitempty' is nullable
  • file
    • Can use commonly used *multipart.FileHeader or []*multipart.FileHeader
    • default media type 'multipart/form-data'
    • Value is an alias for a field, 'omitempty' is nullable
  • body
    • The values are xml and json, Multiple uses ',' segmentation
    • Value of json is media type 'application/json', xml is media type 'application/xml'
    • Body of tag use value, 'omitempty' is nullable
Structure tag annotation
  • regexp
    • Regular expression of value
    • Equivalent to OpenAPI pattern
  • enum
    • Enumeration of values
    • Limit integer number boolean string type
    • Comma division (,)
  • default
    • Default value
  • example
    • Example value
  • desc
    • Field description
    • Equivalent to OpenAPI description
  • lt
    • Less than value
    • Limit integer number type
    • Equivalent to OpenAPI exclusiveMaximum
  • lte
    • Less than or equal to value
    • Limit integer number type
    • Equivalent to OpenAPI maximum
  • gt
    • Greater than value
    • Limit integer number type
    • Equivalent to OpenAPI exclusiveMinimum
  • gte
    • Greater than or equal to value
    • Limit integer number type
    • Equivalent to OpenAPI minimum
  • multiple
    • Multipliers of values
    • Limit integer number type
  • max
    • The maximum length of the value
    • Limit string array object type
  • min
    • The minimum length of the value
    • Limit string array object type
  • unique
    • The value of the array is unique
    • Limit array type

Response annotation

  • if response is an implementation of the goapi.Response interface, you can set the http Code and header
  • else do not set the header, and set the HTTP code to 200

About

Generate documentation using an API similar to FastAPI in Python

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func HTTPException

func HTTPException(httpCode int, detail string, headers ...map[string]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
	// contains filtered or unexported fields
}

func GoAPI

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

func (*API) AddMiddleware

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

func (*API) HTTPExceptionHandler

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

func (*API) IncludeRouter

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

func (*API) Run

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

func (*API) SetLang

func (a *API) SetLang(lang Lang)

func (*API) SetLogger added in v0.0.2

func (a *API) SetLogger(log Logger)

func (*API) SetResponseMediaType

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

type APP

type APP interface {
	Init()
	Handle(handler func(ctx *Context))
	Run(addr string) error
}

type ApiKey

type ApiKey interface {
	ApiKey()
}

type Context

type Context struct {
	Request *http.Request
	Writer  http.ResponseWriter
	Values  map[string]any
	Log     Logger
	// contains filtered or unexported fields
}

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) Get

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

func (*Context) Next

func (c *Context) Next()

func (*Context) Set

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

func (*Context) SetMiddleware added in v0.0.2

func (c *Context) SetMiddleware(middlewares ...Middleware)

func (*Context) Value

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

type HTTPBasic

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

type HTTPBearer

type HTTPBearer interface {
	HTTPBearer(token string)
}

type HTTPResponse

type HTTPResponse[T any] struct {
	HttpCode int
	Header   map[string]string
	Body     T
}

func (*HTTPResponse[T]) Bytes

func (h *HTTPResponse[T]) Bytes() []byte

func (*HTTPResponse[T]) GetBody

func (h *HTTPResponse[T]) GetBody() any

func (*HTTPResponse[T]) GetHeaders

func (h *HTTPResponse[T]) GetHeaders() map[string]string

func (*HTTPResponse[T]) GetHttpCode

func (h *HTTPResponse[T]) GetHttpCode() int

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
}

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 {
	Bytes() []byte
	GetBody() any
	GetHttpCode() int
	GetHeaders() map[string]string
}

type ResponseWriter added in v0.0.2

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

func (*ResponseWriter) Header added in v0.0.2

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

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 ','

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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