Categorygithub.com/farseer-go/webapi
modulepackage
0.14.0
Repository: https://github.com/farseer-go/webapi.git
Documentation: pkg.go.dev

# README

webapi 概述

包:"github.com/farseer-go/webapi"

模块:webapi.Module

codecov Build

用于快速构建api服务,带来极简、优雅的开发体验。编写api服务时,不需要使用httpRequest、httpResponse等数据结构。

webapi使用了中间件的管道模型编写,让我们加入非业务逻辑时非常简单。

包含两种风格来提供API服务:

  • MinimalApi:动态API风格(直接绑定到逻辑层)
  • Mvc:Controller、Action风格

使用minimalApi时,甚至不需要UI层来提供API服务。

webapi有哪些功能

  • 支持中间件
  • 入参、出参隐式绑定
  • 支持静态目录绑定
  • ActionFilter过虑器
  • ActionResult抽象结果
  • Area区域设置
  • MinimalApi模式
  • Mvc模式
    • HttpContext上下文
    • Header隐式绑定

大部份情况下,除了main需要配置webapi路由外,在你的api handle中就是一个普通的func函数,不需要依赖webapi组件。webapi会根据func函数出入参隐式绑定数据

func main() {
	fs.Initialize[webapi.Module]("FOPS")
	webapi.RegisterPOST("/mini/hello1", Hello1)
	webapi.RegisterPOST("/mini/hello3", Hello3, "pageSize", "pageIndex")
	webapi.Run()
}

// 使用结构(DTO)来接收入参
// 返回string
func Hello1(req pageSizeRequest) string {
	return fmt.Sprintf("hello world pageSize=%d,pageIndex=%d", req.PageSize, req.PageIndex)
}

// 使用基础参数来接收入参
// 返回pageSizeRequest结构(会自动转成json)
func Hello3(pageSize int, pageIndex int) pageSizeRequest {
    return pageSizeRequest{
        PageSize:  pageSize,
        PageIndex: pageIndex,
    }
}

// 也可以定义一个结构,用于接收参数
type pageSizeRequest struct {
    PageSize  int
    PageIndex int
}

函数中,出入参都会自动绑定数据

如果是application/json,则会自动被反序列化成model,如果是x-www-form-urlencoded,则会将每一项的key/value匹配到model字段中

可以看到,整个过程,不需要json序列化httpRequesthttpResponse的操作。

# Packages

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author

# Functions

Area 设置区域.
GetHttpContext 在minimalApi模式下也可以获取到上下文.
No description provided by the author
PrintRoute 打印所有路由信息到控制台.
RegisterController 自动注册控制器下的所有Action方法.
RegisterDELETE 注册单个Api(支持占位符,例如:/{cateId}/{Id}).
RegisterGET 注册单个Api(支持占位符,例如:/{cateId}/{Id}).
No description provided by the author
RegisterPOST 注册单个Api(支持占位符,例如:/{cateId}/{Id}).
RegisterPUT 注册单个Api(支持占位符,例如:/{cateId}/{Id}).
RegisterRoutes 批量注册路由.
Run 运行Web服务(默认8888端口).
SetHttpContext 设置当前上下文.
UseApiDoc 是否开启Api文档.
UseApiResponse 让所有的返回值,包含在core.ApiResponse中.
UseCors 使用CORS中间件.
UseHealthCheck 【GET】开启健康检查(默认route = "/healthCheck").
UsePprof 是否同时开启pprof.
UseSession 开启Session.
UseStaticFiles 支持静态目录,在根目录./wwwroot中的文件,直接以静态文件提供服务.
UseTLS 使用https.
UseValidate 使用字段验证器.
No description provided by the author

# Structs

No description provided by the author
Route 路由配置.

# Interfaces

No description provided by the author