All skills
gogf avatar

/goframe-v2

@911705d
by GoFramegogf/skills81 stars
3

GoFrame v2 development skill. Use only when the target Go project uses or is explicitly adopting GoFrame v2: the nearest go.mod requires github.com/gogf/gf/v2, existing Go files import github.com/gogf/gf/v2 or any github.com/gogf/gf/v2/... component package, or the user asks to scaffold, migrate, or build with GoFrame. Trigger for GoFrame-backed Go work such as APIs/controllers/services, middleware, routing/config, ORM/DAO/DO/entity/database operations, gf CLI/codegen, HTTP/gRPC services, and microservice conventions. Do not trigger for generic Go projects without GoFrame evidence, frontend-only work, shell scripts, or unrelated infrastructure tasks.

Use this Skill: https://skilld.dev/gh/gogf/skills/goframe-v2

This session only. Nothing lands on disk.

references快速开始生成接口文档.md

≈1.6k tokens on demand. Your agent reads this file only when SKILL.md points to it.

使用GoFrame框架自动化生成接口文档非常简单。

我们首先对前面章节的接口数据结构进行简单的完善,以便生成的接口文档更加优雅。

接口定义完善

type HelloReq struct {
    g.Meta `path:"/" method:"get" tags:"Test" summary:"Hello world test case"`
    Name   string `v:"required" json:"name" dc:"姓名"`
    Age    int    `v:"required" json:"age"  dc:"年龄"`
}
type HelloRes struct {
    Content string `json:"content" dc:"返回结果"`
}

可以看到,基于前面章节的接口数据结构定义,我们在其g.Meta中增加了两个标签:

  • tags: 该接口属于哪个分类,或者接口模块。
  • summary: 接口描述。

:::info 这些标签都是OpenAPIv3标准接口协议的规范字段,在开发手册对应章节有关于接口文档生成以及标签的详细讲解,我们这里不作过多介绍。 :::

完整代码示例

package main

import (
    "context"
    "fmt"

    "github.com/gogf/gf/v2/frame/g"
    "github.com/gogf/gf/v2/net/ghttp"
)

type Response struct {
    Message string      `json:"message" dc:"消息提示"`
    Data    interface{} `json:"data"    dc:"执行结果"`
}

type HelloReq struct {
    g.Meta `path:"/" method:"get" tags:"Test" summary:"Hello world test case"`
    Name   string `v:"required" json:"name" dc:"姓名"`
    Age    int    `v:"required" json:"age"  dc:"年龄"`
}
type HelloRes struct {
    Content string `json:"content" dc:"返回结果"`
}

type Hello struct{}

func (Hello) Say(ctx context.Context, req *HelloReq) (res *HelloRes, err error) {
    res = &HelloRes{
        Content: fmt.Sprintf(
            "Hello %s! Your Age is %d",
            req.Name,
            req.Age,
        ),
    }
    return
}

func ResponseMiddleware(r *ghttp.Request) {
    r.Middleware.Next()

    var (
        msg string
        res = r.GetHandlerResponse()
        err = r.GetError()
    )
    if err != nil {
        msg = err.Error()
    } else {
        msg = "OK"
    }
    r.Response.WriteJson(Response{
        Message: msg,
        Data:    res,
    })
}

func main() {
    s := g.Server()
    s.Group("/", func(group *ghttp.RouterGroup) {
        group.Middleware(ResponseMiddleware)
        group.Bind(
            new(Hello),
        )
    })
    s.SetOpenApiPath("/api.json")
    s.SetSwaggerPath("/swagger")
    s.SetPort(8000)
    s.Run()
}

在本示例中:

  • 通过s.SetOpenApiPath("/api.json")启用OpenAPIv3的接口文档生成,并指定生成的文件路径/api.json。
  • 通过s.SetSwaggerPath("/swagger")启用内置的Swagger接口文档UI,并指定客访问的UI地址为/swagger。内置的Swagger UI可自定义修改,具体可参考开发手册相应章节。

关于OpenAPIv3

OpenAPIv3是目前业内的接口文档标准协议,用于接口文档的定义,通常使用json格式生成。该接口文档json文件可以用许多接口管理工具打开,例如Swagger UI/PostMan/APIFox等等。

关于Swagger

Swagger是常用的接口文档UI展示工具,支持多种接口文档格式,最常用的接口文档格式当然是OpenAPIv3。

在本示例中,如果需要使用内置的Swagger UI查看接口文档,需要同时启用OpenAPIv3和Swagger UI。即调用SetOpenApiPath和SetSwaggerPath方法设置对应的访问路径。

执行结果

终端输出

执行后,终端输出:

2024-10-28 21:56:42.747 [INFO] pid[87280]: http server started listening on [:8000]
2024-10-28 21:56:42.747 [INFO] {d84db2976ea202187ba40f5d0657e4d7} swagger ui is serving at address: http://127.0.0.1:8000/swagger/
2024-10-28 21:56:42.747 [INFO] {d84db2976ea202187ba40f5d0657e4d7} openapi specification is serving at address: http://127.0.0.1:8000/api.json

  ADDRESS | METHOD |   ROUTE    |                        HANDLER                        |    MIDDLEWARE      
----------|--------|------------|-------------------------------------------------------|--------------------
  :8000   | GET    | /          | main.(*Hello).Say                                     | main.Middleware    
----------|--------|------------|-------------------------------------------------------|--------------------
  :8000   | ALL    | /api.json  | github.com/gogf/gf/v2/net/ghttp.(*Server).openapiSpec |                    
----------|--------|------------|-------------------------------------------------------|--------------------
  :8000   | ALL    | /swagger/* | github.com/gogf/gf/v2/net/ghttp.(*Server).swaggerUI   | HOOK_BEFORE_SERVE  
----------|--------|------------|-------------------------------------------------------|--------------------

我们可以看到,终端输出的提示信息发生了一些变化:

  • 终端输出了swagger的地址http://127.0.0.1:8000/swagger/点击该地址可以直接打开Swagger UI界面。
  • 终端输出了openapi的接口文档地址http://127.0.0.1:8000/api.json,该地址文件可以使用很多接口文档UI查看工具打开。
  • 路由信息也多了两行地址,对应的是swagger和openapi的地址。其中swagger的路由地址使用了Server的HOOK钩子特性,HOOK是一种比中间件更加自由的请求拦截方式,可以同时拦截动态接口和静态资源请求。有固定的几种埋点HOOK,这里使用的埋点是HOOK_BEFORE_SERVE,具体的细节请查看开发手册中Web Server的相关章节,这里不展开介绍。

Swagger UI

我们点击swagger地址 http://127.0.0.1:8000/swagger/ 查看:

  • 由于我们只定义了一个接口,所以Swagger页面只看一个接口定义,在Test分类下展示的具体的接口名称Hello world test case。

  • 在接口详情中,展示了接口的输入与输出数据结构。甚至对于输入的数据结构,GoFrame生成的接口文档能够自动识别其校验规则,比如是否必需参数。并展示了各个参数的数据类型、参数描述。

学习小结

通过本章节的学习,我们学习到了以下几点知识:

  • 通过对路由接口进行规范化的输入输出数据结构定义,可以很好地维护接口,特别是业务较复杂、接口比较多的项目。
  • 通过GoFrame框架自动化接口文档生成特性,可以很方便地生成基于OpenAPIv3标准化的接口文档、Swagger UI展示页面,极大降低接口维护成本、提高服务间协作效率。

Source: SKILL.md on GitHub

1 alert16d5 checks · Risk MEDIUM
  • Gen Agent Trust Hub16d

    The skill provides a comprehensive development guide and code examples for the GoFrame v2 framework. While highly informative for Go developers, it contains several examples with hardcoded placeholder secrets, tokens, and specific local file paths to sensitive configuration files (like Kubernetes credentials). These elements are provided for demonstration purposes but represent insecure practices if used in production without modification.

  • Socket16d

    5 alerts: gptSecurity, gptAnomaly

  • Snyk16d

    Risk: LOW · No issues

  • Runlayer6mo

    227/949 files flagged

  • ZeroLeaks5mo

    Score: 93/100 · 2 sections analyzed

Signed by skilld at 911705d. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 4 months ago.

Steadyupdated 4 months ago
  • Go
  • Database
  • goframe
  • orm
  • http
  • grpc
  • microservices
  • crud
  • scaffolding
  • middleware

README badge

README badge for gogf/skills

Provides instruction and conventions for developing with GoFrame v2, a modular Go framework for building HTTP and gRPC services, microservices, and database operations using its ORM, CLI tooling, and project scaffolding. Use this skill when the target project has GoFrame v2 as a dependency or when the user requests scaffolding, migrations, or service development with GoFrame conventions.

Generated from the current SKILL.md.

When should I use this skill?
Use this skill only when your Go project uses GoFrame v2, indicated by github.com/gogf/gf/v2 in go.mod or imports. Do not use for generic Go projects, frontend work, or infrastructure tasks unrelated to GoFrame.
Should I manually set created_at and updated_at fields?
No. GoFrame automatically writes created_at on insert and updated_at on insert/update/save. Manually setting these fields is redundant and violates project conventions.
What should I use for database operations instead of g.Map?
Always use DO objects from internal/model/do/. DO struct fields are interface{}, unset fields remain nil and are automatically ignored by the ORM.
How does soft delete work in GoFrame?
Call Delete() on the DAO; GoFrame automatically converts it to UPDATE SET deleted_at = NOW(). Queries automatically filter out soft-deleted rows without requiring manual WhereNull conditions.
Where should I implement business logic?
Implement business logic directly in the service/ directory. Do not use the logic/ directory unless explicitly requested.

Generated from the current SKILL.md. These answers refresh after source changes.