network

package
v0.0.0-...-3377335 Latest Latest
Warning

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

Go to latest
Published: Apr 25, 2024 License: MulanPSL-2.0 Imports: 13 Imported by: 0

README

network

网络基础库,包含路由处理工具,以及应答统一格式等。

类型:

  • Response:通用应答格式。

接口:

  • Router:路由统一处理函数。
  • SuccessResponse:返回成功信息。
  • FailureResponse:返回失败信息。
  • Post:发送POST请求。
  • PostFile:发送POST文件请求。

Documentation

Index

Constants

View Source
const (
	ResponseCodeOK   = 0 // 成功
	ResponseCodeFail = 1 // 通用失败
)

常用状态码

Variables

This section is empty.

Functions

func Failure

func Failure(c *gin.Context, code int, format string, args ...interface{})

失败并终止中间件处理流程

func FailureGeneric

func FailureGeneric(c *gin.Context, format string, args ...interface{})

未知业务错误

func Post

func Post[R any](
	baseUrl string,
	apiUrl string,
	headers map[string]interface{},
	requestBody interface{},
	hasResponse bool,
) (rsp R, err error)

发送内部请求(POST),并解析返回值。

baseUrl:基地址
apiUrl:URL后面的相对地址
headers:HTTP头信息,大小写敏感
requestBody:请求的Body
hasResponse:是否解析应答

func PostFile

func PostFile[R any](
	baseUrl string,
	apiUrl string,
	headers map[string]interface{},
	requestBodyKey string,
	requestBody interface{},
	fileKey string,
	fileName string,
	fileReader io.Reader,
	hasResponse bool,
) (rsp R, err error)

发送内部文件请求(POST),并解析返回值。

baseUrl:基地址
apiUrl:URL后面的相对地址
headers:HTTP头信息,大小写敏感
requestBodyKey:请求Body存放在表单的哪个键
requestBody:请求Body
fileKey:文件存放在表单的哪个键
fileName:文件名称
fileReader:文件读取句柄
hasResponse:是否解析应答

func Recovery

func Recovery() gin.HandlerFunc

恢复panic的中间件

func Router

func Router[P any, R any](
	handler RouterHandler[P, R],
	opt *RouterOptions,
) gin.HandlerFunc

路由封装函数

func Success

func Success[T any](c *gin.Context, data T)

返回成功消息

Types

type Response

type Response[T any] struct {
	Code      int    `json:"code"`           // 状态码
	Message   string `json:"message"`        // 错误消息
	Data      T      `json:"data,omitempty"` // (code=OK) 数据区
	Timestamp int64  `json:"timestamp"`      // 时间戳
}

返回结果格式

func (Response[T]) IsSuccess

func (r Response[T]) IsSuccess() bool

type RouterHandler

type RouterHandler[P any, R any] func(*gin.Context, P) (R, error)

通用路由处理函数

type RouterOptions

type RouterOptions struct {
	FileJsonKey string // 有值时表示是文件路由,记录Json字段存放的PostForm键名称
	NoRequest   bool   // 无需解析请求,默认值false
	NoResponse  bool   // 无需返回应答,默认值false
}

通用路由处理的选项

Jump to

Keyboard shortcuts

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