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.1k tokens on demand. Your agent reads this file only when SKILL.md points to it.

本章节我们将使用固定的数据格式返回结果,无论路由函数执行成功还是失败,我们以json格式返回结果给调用端。

返回格式定义

我们定义一个统一的数据结构:

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

由于我们需要返回json数据格式,因此我们给每个字段都加上json标签。

接口数据结构

type HelloReq struct {
    g.Meta `path:"/" method:"get"`
    Name   string `v:"required" json:"name" dc:"姓名"`
    Age    int    `v:"required" json:"age"  dc:"年龄"`
}
type HelloRes struct {
    Content string `json:"content" dc:"返回结果"`
}
  • 我们给HelloRes增加了一个Content属性,用于路由函数返回具体的数据。
  • 由于需要通过json数据格式返回数据,因此所有的属性字段均增加json标签。

路由函数

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
}

我们这里通过HelloRes返回数据结构返回执行结果,而不是像前面的示例那样通过g.RequestFromCtx(ctx)获取原始的请求对象直接Write结果。

中间件定义

func Middleware(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,
    })
}

在该中间件中:

  • 通过r.GetHandlerResponse()方法获取路由函数的执行结果,即路由函数返回的第一个结果参数*HelloRes。
  • 通过r.GetError()获取路由函数的执行状态,即路由函数返回的第二个结果参数error,如果该结果不为nil,表示该路由函数执行产生了错误。
  • 通过r.Response.WriteJson将结果整合到统一的返回数据结构Response,并编码为json格式返回给调用端。

完整示例代码

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"`
    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.SetPort(8000)
    s.Run()
}

该示例中的所有代码我们已经做过了介绍,我们直接执行即可。

执行结果

运行后,我们访问 http://127.0.0.1:8000/?name=john&age=18 可以看到,页面输出结果符合预期。

我们尝试一下错误的参数请求 http://127.0.0.1:8000/ 可以看到,页面输出了错误的结果信息,返回数据类型也是json格式。

学习小结

在本章节中,我们学会了使用常用的json格式对接口进行统一的数据格式封装,这在有着成百上千接口的业务项目中是非常有必要的。

可以看到,我们已经将参数完整地进行了结构化,结构中带有详细的输入输出参数描述、类型定义甚至数据校验规则, 那么我们能否基于这些信息自动化地生成接口文档呢?答案也是肯定的,我们将在下一章节介绍。

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.