goapi

package module
v0.0.5 Latest Latest
Warning

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

Go to latest
Published: Jul 17, 2024 License: MIT Imports: 24 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" {
		goapi.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" {
		goapi.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" {
		goapi.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

Error corresponding comment

goapi.HTTPException(404, "error message")
  • Specific return information can be configured using the 'HTTPExceptionHandler' method
  • The first parameter is the HTTP status code, the second is the error message, and the third is the header setting returned

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

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

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

IncludeRouter It is a function that introduces routing structures

func (*API) Run

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

Run It is an execution function

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) Static added in v0.0.4

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

Static serves files from the given file system root.

type APP

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

type ApiKey

type ApiKey interface {
	ApiKey()
}

ApiKey verification interface

type Context

type Context struct {
	Request *http.Request
	Writer  http.ResponseWriter
	Values  map[string]any
	// 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) Logger added in v0.0.3

func (c *Context) Logger() Logger

func (*Context) Next

func (c *Context) Next()

func (*Context) Set

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

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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