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.

referencesWEB服务开发路由管理路由管理-路由规则.md

GoFrame 框架自建了非常强大的路由功能,提供了比任何同类框架更加出色的路由特性,支持流行的命名匹配规则、模糊匹配规则及字段匹配规则,并提供了优秀的优先级管理机制。

一个示例

在真正开启本章的核心内容之前,我们先来看一个简单的动态路由使用示例:

package main

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

func main() {
    s := g.Server()
    s.BindHandler("/:name", func(r *ghttp.Request){
       r.Response.Writeln(r.Router.Uri)
    })
    s.BindHandler("/:name/update", func(r *ghttp.Request){
        r.Response.Writeln(r.Router.Uri)
    })
    s.BindHandler("/:name/:action", func(r *ghttp.Request){
        r.Response.Writeln(r.Router.Uri)
    })
    s.BindHandler("/:name/*any", func(r *ghttp.Request){
       r.Response.Writeln(r.Router.Uri)
    })
    s.BindHandler("/user/list/{field}.html", func(r *ghttp.Request){
        r.Response.Writeln(r.Router.Uri)
    })
    s.SetPort(8199)
    s.Run()
}

以上示例中展示了 goframe 框架支持的三种模糊匹配路由规则, :name、 *any、 {field} 分别表示 命名匹配规则、 模糊匹配规则 及 字段匹配规则。不同的规则中使用 / 符号来划分层级,路由检索采用 深度优先算法,层级越深的规则优先级也会越高。我们运行以上示例,通过访问几个 URL 来看看效果:

URL                                         结果
http://127.0.0.1:8199/user/list/2.html      /user/list/{field}.html
http://127.0.0.1:8199/user/update           /:name/update
http://127.0.0.1:8199/user/info             /:name/:action
http://127.0.0.1:8199/user                  /:name/*any

在这个示例中我们也可以看到,由于优先级的限制,路由规则 /:name 会被 /:name/*any 规则覆盖,将会无法被匹配到,所以在分配路由规则的时候,需要进行统一规划和管理,避免类似情况的产生。

注册规则

路由注册参数

最基础的 路由绑定方法是 BindHandler 方法,我们来看一下之前一直使用的 BindHandler 的原型:

func (s *Server) BindHandler(pattern string, handler interface{})
pattern 参数

其中的 pattern 为路由注册规则字符串,在其他路由注册方法中也会使用到,参数格式如下:

[HTTPMethod:]路由规则[@域名]

其中 HTTPMethod( GET/PUT/POST/DELETE/PATCH/HEAD/CONNECT/OPTIONS/TRACE)和 @域名 为 非必需参数,大部分场景下直接给定路由规则参数即可, BindHandler 会自动绑定 所有的 请求方式,如果给定 HTTPMethod,那么路由规则仅会在该请求方式下有效。 @域名 可以指定生效的域名名称,那么该路由规则仅会在该域名下生效。 :::tip BindHandler 是最原生的路由注册方法,在大部分场景中,我们通常使用 分组路由 方式来管理理由,后续章节将会介绍: 路由注册-分组路由。 :::

handler 参数

其中的 handler 参数通常用于指定路由函数,我们最基础的示例都是使用函数来注册路由,一个路由函数需要满足以下定义,即只要能接收请求对象 ghttp.Request 即可:

func(r *ghttp.Request) {
    // ...
}

我们来看一个例子:

package main

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

func main() {
    s := g.Server()
    // 该路由规则仅会在GET请求下有效
    s.BindHandler("GET:/{table}/list/{page}.html", func(r *ghttp.Request){
        r.Response.WriteJson(r.Router)
    })
    // 该路由规则仅会在GET请求及localhost域名下有效
    s.BindHandler("GET:/order/info/{order_id}@localhost", func(r *ghttp.Request){
        r.Response.WriteJson(r.Router)
    })
    // 该路由规则仅会在DELETE请求下有效
    s.BindHandler("DELETE:/comment/{id}", func(r *ghttp.Request){
        r.Response.WriteJson(r.Router)
    })
    s.SetPort(8199)
    s.Run()
}

其中返回的参数 r.Router 是当前匹配的路由规则信息,访问当该方法的时候,服务端会输出当前匹配的路由规则信息。执行后,我们在终端使用 curl 命令进行测试:

$ curl -XGET http://127.0.0.1:8199/order/list/1.html
{"Domain":"default","Method":"GET","Priority":3,"Uri":"/{table}/list/{page}.html"}

$ curl -XGET http://127.0.0.1:8199/order/info/1
Not Found

$ curl -XGET http://localhost:8199/order/info/1
{"Domain":"localhost","Method":"GET","Priority":3,"Uri":"/order/info/{order_id}"}

$ curl -XDELETE http://127.0.0.1:8199/comment/1000
{"Domain":"default","Method":"DELETE","Priority":2,"Uri":"/comment/{id}"}

$ curl -XGET http://127.0.0.1:8199/comment/1000
Not Found

精准匹配规则

精准匹配规则即 未使用任何动态规则 的规则,如: user、 order、 info 等等这种 确定名称 的规则。在大多数场景下,精准匹配规则会和动态规则一起使用来进行路由注册(例如: /:name/list,其中层级1 :name 为命名匹配规则,层级2 list 是精准匹配规则)。

动态路由规则

动态路由规则分为三种: 命名匹配规则、 模糊匹配规则 和 字段匹配规则。动态路由的底层数据结构是由层级 哈希表 和 双向链表 构建的 路由树,层级哈希表便于高效率地层级匹配 URI;数据链表用于优先级控制,同一层级的路由规则按照优先级进行排序,优先级高的规则排在链表头。底层的路由规则与请求 URI 的匹配计算采用的是正则表达式,并充分使用了缓存机制,执行效率十分高效。

所有匹配到的参数都将会以 Router 参数的形式传递给业务层,可以通过 ghttp.Request 对象的以下方法获取匹配到的路由参数:

func (r *Request) GetRouter(key string, def ...interface{}) *gvar.Var

也可以使用 ghttp.Request.Get 方法获取匹配到的路由参数。

命名匹配规则

使用 :name 方式进行匹配( name 为自定义的匹配名称),对 URI 指定层级的参数进行命名匹配(类似正则 ([^/]+),该 URI 层级必须有值),对应匹配参数会被解析为 Router 参数并传递给注册的服务接口使用。

匹配示例1:

rule: /user/:user

/user/john                match
/user/you                 match
/user/john/profile        no match
/user/                    no match

匹配示例2:

rule: /:name/action

/john/name                no match
/john/action              match
/smith/info               no match
/smith/info/age           no match
/smith/action             match

匹配示例3:

rule: /:name/:action

/john/name                match
/john/info                match
/smith/info               match
/smith/info/age           no match
/smith/action/del         no match
模糊匹配规则

使用 *any 方式进行匹配( any 为自定义的匹配名称),对 URI 指定位置之后的参数进行模糊匹配(类似正则 (.*),该 URI 层级可以为空),并将匹配参数解析为 Router 参数并传递给注册的服务接口使用。

匹配示例1:

rule: /src/*path

/src/                     match
/src/somefile.go          match
/src/subdir/somefile.go   match
/user/                    no match
/user/john                no match

匹配示例2:

rule: /src/*path/:action

/src/                     no match
/src/somefile.go          match
/src/somefile.go/del      match
/src/subdir/file.go/del   match

匹配示例3:

rule: /src/*path/show

/src/                     no match
/src/somefile.go          no match
/src/somefile.go/del      no match
/src/somefile.go/show     match
/src/subdir/file.go/show  match
/src/show                 match
字段匹配规则

使用 {field} 方式进行匹配( field 为自定义的匹配名称),可对 URI 任意位置 的参数进行截取匹配(类似正则 ([\w\.\-]+),该 URI 层级必须有值,并且可以在同一层级进行多个字段匹配),并将匹配参数解析为 Router 参数并传递给注册的服务接口使用。

匹配示例1:

rule: /order/list/{page}.php

/order/list/1.php          match
/order/list/666.php        match
/order/list/2.php5         no match
/order/list/1              no match
/order/list                no match

匹配示例2:

rule: /db-{table}/{id}

/db-user/1                     match
/db-user/2                     match
/db/user/1                     no match
/db-order/100                  match
/database-order/100            no match

匹配示例3:

rule: /{obj}-{act}/*param

/user-delete/10                match
/order-update/20               match
/log-list                      match
/log/list/1                    no match
/comment/delete/10             no match

动态路由示例

package main

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

func main() {
    s := g.Server()
    // 一个简单的分页路由示例
    s.BindHandler("/user/list/{page}.html", func(r *ghttp.Request){
        r.Response.Writeln(r.Get("page"))
    })
    // {xxx} 规则与 :xxx 规则混合使用
    s.BindHandler("/{object}/:attr/{act}.php", func(r *ghttp.Request){
        r.Response.Writeln(r.Get("object"))
        r.Response.Writeln(r.Get("attr"))
        r.Response.Writeln(r.Get("act"))
    })
    // 多种模糊匹配规则混合使用
    s.BindHandler("/{class}-{course}/:name/*act", func(r *ghttp.Request){
        r.Response.Writeln(r.Get("class"))
        r.Response.Writeln(r.Get("course"))
        r.Response.Writeln(r.Get("name"))
        r.Response.Writeln(r.Get("act"))
    })
    s.SetPort(8199)
    s.Run()
}

执行后,我们可以通过 curl 命令或者浏览器访问的方式进行测试,以下为测试结果:

$ curl -XGET http://127.0.0.1:8199/user/list/1.html
1

$ curl -XGET http://127.0.0.1:8199/user/info/save.php
user
info
save

$ curl -XGET http://127.0.0.1:8199/class3-math/john/score
class3
math
john
score

优先级控制

优先级控制按照 深度优先策略,简要计算策略:

  1. 层级越深的规则优先级越高;
  2. 同一层级下,精准匹配优先级高于模糊匹配;
  3. 同一层级下,模糊匹配优先级:字段匹配 > 命名匹配 > 模糊匹配;

我们来看示例(左边的规则优先级比右边高):

/:name                   >            /*any
/user/name               >            /user/:action
/:name/info              >            /:name/:action
/:name/:action           >            /:name/*action
/:name/{action}          >            /:name/:action
/src/path/del            >            /src/path
/src/path/del            >            /src/path/:action
/src/path/*any           >            /src/path

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.