goapi

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 6, 2024 License: MIT Imports: 26 Imported by: 0

README

goapi

Using the HTTP framework of OpenAPI3.1 documentation

English | 中文

usage

go get github.com/goodluckxu-go/goapi

main.go

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

func main() {
	color.NoColor = true // Turn off the default logging console color
	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 {
	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 {
	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"
}


// Implement ApiKey interface
type AdminAuth struct {
	Token  string   `header:"Token"`
	Admin  string          // Define a value and retrieve it from the controller
}

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

Verify multilingual Settings

You can implement the 'goapi.Lang' interface yourself

api.SetLang(&lang.ZhCn{}) // Default 'EnUs' English comments

Log output setting

Set before initializing the api

goapi.SetLogLevel(goapi.LogInfo | goapi.LogWarning)
'goapi.Router' tag field annotation
  • 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 ','
Annotation of parameter structure tag in the method
  • 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
    • The value is for other media types(example 'text/plain'), The type is '[]byte', 'string' or 'io.ReadCloser'
    • Value of json is media type 'application/json', xml is media type 'application/xml'
    • Body of tag use value, 'omitempty' is nullable
    • When the value is 'application/octet-stream', indicates that the body is uploaded as a file
Structure tag annotation
  • regexp
    • Regular expression of value
    • Validator limit string type
    • Equivalent to OpenAPI pattern
  • enum
    • Enumeration of values
    • Validator 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
    • Validator limit integer number type
    • Equivalent to OpenAPI exclusiveMaximum
  • lte
    • Less than or equal to value
    • Validator limit integer number type
    • Equivalent to OpenAPI maximum
  • gt
    • Greater than value
    • Validator limit integer number type
    • Equivalent to OpenAPI exclusiveMinimum
  • gte
    • Greater than or equal to value
    • Validator limit integer number type
    • Equivalent to OpenAPI minimum
  • multiple
    • Multipliers of values
    • Validator limit integer number type
  • max
    • The maximum length of the value
    • Validator limit string array object type
  • min
    • The minimum length of the value
    • Validator limit string array object type
  • unique
    • The value of the array is unique
    • Validator limit array type

Response annotation

if response is an implementation of the goapi.Response interface, you can set some functions
  • HTTPResponse[T] can set httpCode, header, cookie. Content-Type value is 'application/json','application/xml'
  • FileResponse can return downloadable files. Content-Type value is 'application/octet-stream'
  • SSEResponse can return content in Server Sent Events format. Content-Type value is 'text/event-stream'
  • HTMLResponse can return to HTML page. Content-Type value is 'text/html'
  • TextResponse return in text mode, can set header, cookie. Content-Type default value is 'text/plain',resettable Content-Type

Error corresponding comment

response.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 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) 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) 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 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 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 {
	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 ','

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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