ginapi

package module
v0.0.0-...-defef51 Latest Latest
Warning

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

Go to latest
Published: May 31, 2024 License: MIT Imports: 16 Imported by: 0

README

ginapi

About the OpenAPI usage of gin

usage

go get github.com/goodluckxu-go/ginapi

main.go入口文件

import (
    "github.com/gin-gonic/gin"
    "github.com/goodluckxu-go/ginapi"
    "github.com/goodluckxu-go/ginapi/param"
    "github.com/goodluckxu-go/ginapi/response"
    "net/http"
)
func main() {
	app := ginapi.GinAPI(gin.Default(), true)
	app.SetDefaultResponseMediaType(response.Json{}) // return media type, It can also be inherited in the return structure
	app.SetHttpError(func(code int, msg string) response.Response {
		return response.Response{
			HttpStatus: code,
			Data: Test{
				Code: 0,
				Msg:  msg,
			},
		}
	})
	app.IncludeRouter(&UserController{}, "/v1", false)
	_ = app.Run("127.0.0.1:8080")
}

user_controller.go控制器文件

type UserController struct {
}

type UserListRouter struct {
}

func (u *UserListRouter) Router() param.Router {
	return param.Router{
		Methods: []string{http.MethodPost, http.MethodPut},
		Path:    "/user/list/{ID}",
		Tags:    []string{"admin"},
		Summary: "test api",
	}
}

func (u *UserController) List(
	router *UserListRouter, // Registered routing address
	ctx *gin.Context,       // Add context if necessary
	auth *AdminAuth,       // Auth verification
	path *UserListPath      // Path parameter
) Resp {
	fmt.Println(auth.Admin)
	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"
}

Explanation of struct comments

type TestStruct struct {
	Name  string `json:"name" desc:"username"`
	param.Path   // Get the parameters on the path
}
Structure tag annotation
  • required
    • Value is mandatory
  • 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 maximum + exclusiveMaximum=true
  • lte
    • Less than or equal to value
    • Limit integer number type
    • Equivalent to OpenAPI maximum + exclusiveMaximum=false
  • gt
    • Greater than value
    • Limit integer number type
    • Equivalent to OpenAPI minimum + exclusiveMinimum=true
  • gte
    • Greater than or equal to value
    • Limit integer number type
    • Equivalent to OpenAPI minimum + exclusiveMinimum=false
  • 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
Request parameter structure
  • param.Path
    • Get the parameters on the path
  • param.Query
    • Get the parameters on the query
  • param.Header
    • Get the parameters on the header
  • param.Cookie
    • Get the parameters on the cookie
  • param.FormUrlencoded
    • Get the body of Content-Type: application/x-www-form-urlencoded
  • param.FormData
    • Get the body of Content-Type: multipart/form-data
  • param.BodyJson
    • Get the body of Content-Type: application/json
  • param.BodyXml
    • Get the body of Content-Type: application/xml
Return parameter structure
  • response.Json
    • Get the media type of application/json
  • response.Xml
    • Get the media type of application/xml

About

Generate documentation using an API similar to FastAPI in Python

Documentation

Index

Constants

View Source
const CodeValidError = 422

Variables

This section is empty.

Functions

func SetLang

func SetLang(l string)

Types

type API

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

func GinAPI

func GinAPI(engine *gin.Engine, isDocs bool, docsPath ...string) (api *API)

func (*API) IncludeRouter

func (a *API) IncludeRouter(router any, prefix string, isDocs bool, handlers ...gin.HandlerFunc)

func (*API) Run

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

func (*API) SetDefaultResponseMediaType

func (a *API) SetDefaultResponseMediaType(data ...response.Data)

func (*API) SetHttpError

func (a *API) SetHttpError(errorFunc func(code int, msg string) response.Response)

func (*API) SetOpenAPI

func (a *API) SetOpenAPI(openAPI *OpenAPI)

func (*API) Use

func (a *API) Use(middleware ...gin.HandlerFunc)

type Contact

type Contact struct {
	Name  string
	URL   string
	Email string
}

type ExternalDocs

type ExternalDocs struct {
	Description string
	URL         string
}

type Info

type Info struct {
	Title          string // Required
	Description    string
	TermsOfService string
	Contact        *Contact
	License        *License
	Version        string // Required
}

type License

type License struct {
	Name string
	URL  string
}

type OpenAPI

type OpenAPI struct {
	Info         *Info
	Servers      []Server
	Tags         []Tag
	ExternalDocs *ExternalDocs
}

type Server

type Server struct {
	URL         string
	Description string
	Variables   map[string]*ServerVariable
}

type ServerVariable

type ServerVariable struct {
	Enum        []string
	Default     string
	Description string
}

type Tag

type Tag struct {
	Name         string
	Description  string
	ExternalDocs *ExternalDocs
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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