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

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

为了解决上一章节遗留的疑问:如何捕获返回的错误对象并作自定义的错误处理。 在本章节中,我们将会先简单介绍Web Server的中间件特性,再回答这个疑问。

中间件介绍

中间件是一种拦截器设计,在Web Server中可以拦截请求和返回结果,并在其前后进行自定义处理逻辑。

中间件的定义和普通的路由函数一样,但是可以在 Request 参数中使用 Middleware 属性对象来控制请求流程。

中间件的类型分为两种:前置中间件和后置中间件。前置即在路由服务函数调用之前调用,后置即在其后调用。

func Middleware(r *ghttp.Request) {
    // 前置中间件处理逻辑 
    r.Middleware.Next()
    // 后置中间件处理逻辑
}

在中间件中执行完成处理逻辑后,使用 r.Middleware.Next() 方法进一步执行下一个流程; 如果这个时候直接退出不调用 r.Middleware.Next() 方法的话,将会退出后续的执行流程(例如可以用于请求的鉴权处理)。

使用中间件

我们使用中间件对上一章节的程序进行简单的改造,如下:

package main

import (
    "context"

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

type HelloReq struct {
    g.Meta `path:"/" method:"get"`
    Name   string `v:"required" dc:"姓名"`
    Age    int    `v:"required" dc:"年龄"`
}
type HelloRes struct{}

type Hello struct{}

func (Hello) Say(ctx context.Context, req *HelloReq) (res *HelloRes, err error) {
    r := g.RequestFromCtx(ctx)
    r.Response.Writef(
        "Hello %s! Your Age is %d",
        req.Name,
        req.Age,
    )
    return
}

func ErrorHandler(r *ghttp.Request) {
    // 执行路由函数
    r.Middleware.Next()
    // 判断是否产生错误
    if err := r.GetError(); err != nil {
        r.Response.Write("error occurs: ", err.Error())
        return
    }
}

func main() {
    s := g.Server()
    s.Group("/", func(group *ghttp.RouterGroup) {
        group.Middleware(ErrorHandler)
        group.Bind(
            new(Hello),
        )
    })
    s.SetPort(8000)
    s.Run()
}
  • 我们定义了一个错误处理的中间件ErrorHandler,在该中间件中我们先通过r.Middleware.Next()执行路由函数流程, 随后通过r.GetError()获取路由函数是否有错误产生。如果产生错误,那么直接输出错误信息。
  • 在路由注册中,我们通过group.Middleware(ErrorHandler)给该分组路由下的所有注册的路由,都绑定了错误处理的中间件。

执行结果

运行后,终端输出:

2024-11-06 22:30:06.927 [INFO] pid[35434]: http server started listening on [:8000]
2024-11-06 22:30:06.927 [INFO] {905637567a67051830833b2189796dda} openapi specification is disabled

  ADDRESS | METHOD | ROUTE |      HANDLER      |    MIDDLEWARE      
----------|--------|-------|-------------------|--------------------
  :8000   | GET    | /     | main.(*Hello).Say | main.ErrorHandler  
----------|--------|-------|-------------------|--------------------

这里的MIDDLEWARE部分多了一个main.ErrorHandler方法,表示该路由绑定的中间件名称。

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

我们尝试一下错误的参数请求 http://127.0.0.1:8000/ 可以看到,页面也输出了错误的提示信息。

学习小结

我们使用中间件对请求错误进行自定义的处理,并捕获校验错误返回自定义的错误信息。 可以看到,中间件的功能非常灵活且强大,当然不仅仅局限于处理校验错误这种小场景。

试想一下,假如我们的项目中有很多接口,通常这些接口的输出格式都是固定的,例如都是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.