Beego 路由
Golang Beego BeegoNotes 2021-08-02基础路由
web.Get(router, web.HandleFunc)
web.Post(router, web.HandleFunc)
web.Put(router, web.HandleFunc)
web.Patch(router, web.HandleFunc)
web.Head(router, web.HandleFunc)
web.Options(router, web.HandleFunc)
web.Delete(router, web.HandleFunc)
web.Any(router, web.HandleFunc)
控制器路由
// func Router(rootpath string, c ControllerInterface, mappingMethods ...string) *HttpServer {
// return BeeApp.Router(rootpath, c, mappingMethods...)
// }
beego.Router("/admin", &admin.UserController{})
- 默认匹配
/:id,/?:id - 类型匹配
/:id:int,/:id:string - 正则匹配
/:id([0-9]+) - 星号匹配
/username/*=>:splat变量
/username/*.*=>:path变量和:ext变量
取变量的方式:
c.Ctx.Input.Param(":id")
mappingMethods
映射 HTTP 方法到指定方法。
- 支持基础路由中提到到八种方法(Any 用星号代替,优先级最低)。
- 如果不指定这个参数,会映射 GET 请求到
Get方法,以此类推。 - 应该不支持指定多个方法。
- 应该不支持重复指定方法。
web.Router("/api/food",&RestController{},"get:ListFood")
web.Router("/api/food",&RestController{},"post:CreateFood")
web.Router("/api/food",&RestController{},"put:UpdateFood")
web.Router("/api/food",&RestController{},"delete:DeleteFood")
web.Router("/api",&RestController{},"get,post:ApiFunc")
web.Router("/api/food",&RestController{},"get:ListFood;post:CreateFood;put:UpdateFood;delete:DeleteFood")
注意:控制器可以声明 URLMapping 方法,比 mapptingMethods 参数通过反射实现更加高效。
func (c *CMSController) URLMapping() {
c.Mapping("StaticBlock", c.StaticBlock)
c.Mapping("AllBlock", c.AllBlock)
}
自动路由
web.AutoRouter(&controllers.ObjectController{})
URL 采用 /:controller/:method 前缀的方式,后面的部分会转化成 map 参数 (.Ctx.Input.Params)。
method 不区分大小写,对应的处理方法名首字母大写,比如 login -> Login。
注意:/system/config.json 对应到 SystemController.Config 方法,后缀通过 .Ctx.Input.Param(":ext") 获取。
注解路由
- 2.0 开始支持,dev 模式生效
- 自动扫描指定目录,生成
routers/commentsRouter.go文件 CommentRouterPath配置扫描目录
web.Include(&CMSController{})
相应的控制器需要添加这样格式的注解:
// @router /staticblock/:key [get]
Beego 框架: 入门
Golang Beego BeegoNotes 2021-07-07照着官网文档 http://beego.vip 过一遍。
PS: 我之前看的网址是 beego.me, 不知道为啥换了域名。
Go 微服务生态
Golang 微服务 分布式 2021-06-30micro
曾经最优秀的,最有前途的 Go 微服务框架。
但是后来发生了一些事...
框架的所有者是 Micro 公司,在 v3 的时候(2020 年下半年),他们决定更改项目定位。
公司运营一个云平台,叫做 m3o,专门提供 micro 项目托管,概念叫做 Micro as a Service。
新版本 micro/micro 目标由
微服务框架改成云原生平台,并且协议由 Apache License 2.0 变更成了 Polyform Shield License(我查了一下,这个协议大意是说如果使用者和所有者发生竞争,则授权取消)。
原项目 microhq/go-micro 进行归档,不再维护。
后来项目转给了他们公司 CTO 账户下 asim/go-micro ,继续维护。
再后来项目更名为 nitro (asim/nitro, gonitro/nitro),还搞了官网啥的。
再后来又放弃了,退回 asim/go-micro。
乱!
云原生就云原生,原有项目没有精力维护也没什么关系,做出这些决定一会儿一变,真是作得一批。
新协议更加是令人无语,杜绝竞争这一条就是堵住了所有商业使用的可能性(据说 nitro 时期也曾一度变更为 Polyform 协议)。
总之,我觉得这个框架要被玩死。
如果像我一样刚接触 Go 微服务,我觉得可以跳过 micro,或者仅用于学习参考。
gokit
A standard library for microservices.
https://github.com/go-kit/kit
它的定位和 micro 不一样,micro 是一个大而全的微服务框架,而 gokit 是一些在微服务中有用的工具,用于开发自己的框架。
国产项目
kratos
go-kratos 是一个基于 Go 语言的轻量级微服务开发框架,由 Bilibili 交给开源社区维护,采用 MIT 开源协议。项目致力于提供云原生应用开发所需的基础能力,帮助开发团队快速构建结构清晰、易于测试和维护的后端服务。
核心功能包括:HTTP/gRPC 双协议支持,通过 Protocol Buffers(Protobuf)定义 API 并生成代码;提供中间件机制,支持日志、认证、参数校验、链路追踪和指标监控;支持可插拔的配置管理、服务注册与发现,以及统一的错误处理机制。框架不强制绑定数据库、ORM 或特定基础设施,便于按需集成现有技术栈。
go-kratos 适合构建微服务、内部 API 服务及大型后端系统。项目还提供 kratos-layout 参考模板,包含分层架构、依赖注入和代码生成示例,可作为新项目的脚手架。需要注意的是,Kratos 主要解决服务端基础架构问题,并不直接提供完整的用户中心、权限管理或管理后台。
项目地址:github.com/go-kratos/kratos
Kratos 的设计核心是:框架提供统一接口和基础机制,具体基础设施通过标准库、独立 Go Module 或外部服务接入。它不是开箱即用的完整业务后台,也不会强制绑定数据库、缓存或注册中心。
| 功能模块 | 核心技术 / 依赖 | 实现方案 |
|---|---|---|
| HTTP 服务 | net/http、Kratos HTTP Transport |
封装 HTTP Server、路由、请求上下文和中间件 |
| gRPC 服务 | google.golang.org/grpc |
基于 gRPC Server、Interceptor 和 Protobuf 生成代码 |
| API 定义与代码生成 | Protobuf、protoc、protoc-gen-go、Kratos CLI |
先定义 .proto,再生成请求结构、客户端及服务端接口 |
| 依赖注入 | Google Wire(脚手架常用) | 在启动阶段组装 Repository、Service、Transport 等对象 |
| 日志 | Kratos Log 接口、Go log/slog |
统一日志接口,具体输出后端可以替换 |
| 请求校验 | Protobuf 校验规则、Validate Middleware | 根据请求结构执行参数校验,失败时返回统一错误 |
| 身份认证 | JWT Middleware(Contrib) | 校验 Token、提取身份信息;用户登录和 Token 签发由业务实现 |
| 授权 | Casbin | - |
| 权限控制 | Middleware、业务授权逻辑 | 在接口层进行访问控制;复杂 RBAC 需要自行集成授权组件 |
| 链路追踪 | OpenTelemetry | 通过 Middleware 传播 Trace Context,采集跨服务调用链 |
| 指标监控 | OpenTelemetry Metrics、Prometheus 等 | 采集请求数量、耗时、错误率等指标,并接入监控系统 |
| 配置管理 | Kratos Config、YAML 等 | 统一加载配置;远程配置通过独立适配模块(Apollo、etcd、Nacos、Consul)接入 |
| 服务注册与发现 | registry 接口、etcd / Consul / Nacos 等 |
实现注册、服务发现和实例变更监听 |
| 限流与熔断 | Kratos Middleware | 服务端限流、客户端熔断;分布式限流通常需要额外实现或集成 |
| 错误处理 | Kratos Errors、HTTP/gRPC 状态映射 | 统一错误码和错误信息,映射为协议对应的响应 |
| 编码与序列化 | JSON Codec、Protobuf | 统一请求和响应编码,可扩展其他 Codec |
| 数据持久化 | 自选 SQL 驱动、数据库或 ORM | Kratos 不内置业务 Repository,应用自行实现数据访问层 |
- Transport 层:HTTP / gRPC · Middleware · API 校验
- Service 层:业务逻辑 · 认证授权 · 错误处理
- Data / Repository 层:数据库 · 缓存 · 外部 API · 消息队列
- 基础设施:配置、日志、指标、链路追踪、服务发现
业务层依赖抽象接口,基础设施层负责具体实现,启动入口负责依赖组装:
type UserRepository interface {
Create(ctx context.Context, name string) error
}
// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
// 用户业务逻辑
type UserService struct {
repo UserRepository
}
func NewUserService(repo UserRepository) *UserService {
return &UserService{repo: repo}
}
func (s *UserService) CreateUser(
ctx context.Context, name string,
) error {
return s.repo.Create(ctx, name)
}
// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
type MySQLUserRepository struct {
db *sql.DB
}
func (r *MySQLUserRepository) Create(
ctx context.Context, name string,
) error {
_, err := r.db.ExecContext(
ctx,
"INSERT INTO users (name) VALUES (?)",
name,
)
return err
}
Jupiter
注意:这个项目 2024 年开始就不怎么活跃了。
Jupiter 是斗鱼开源的 Go 微服务治理框架,项目地址:douyu/jupiter。它不仅提供 HTTP、gRPC 等服务开发能力,更注重微服务在生产环境中的运行、监控与治理,适用于中大型后端系统和分布式业务平台。
Jupiter 的核心功能包括:服务通信与治理,支持 HTTP、gRPC、服务注册发现、负载均衡、限流、超时和重试等机制;可观测性,提供统一日志、指标采集、分布式链路追踪和错误处理能力;配置管理,支持配置驱动的组件初始化与运行时管理;开发工具链,提供项目脚手架、标准化项目模板和开发调试工具,降低项目搭建与维护成本。
其设计理念是以应用为中心,对常用第三方组件进行统一封装,减少基础设施差异对业务代码的影响,并将监控、配置和治理能力整合到应用运行时中。
适用场景: 需要统一技术栈、完善可观测性和服务治理能力的 Go 微服务体系。相比 Gin、Echo 等侧重 HTTP 请求处理的 Web 框架,Jupiter 的定位更偏向企业级微服务基础设施。代价是引入的组件和治理体系更多,轻量级单体应用未必需要完整采用。
go-zero
其作者在知乎上比较活跃:万俊峰Kevin, Title 是晓黑板 CTO。
go-zero 是一个基于 Go 语言开发的开源微服务框架,旨在帮助开发者快速构建高性能、高可用、易于维护的分布式系统。它提供 API 网关、RPC 服务、服务发现、负载均衡、限流熔断、超时控制、缓存、链路追踪等能力,覆盖微服务从开发到运行的主要环节。
go-zero 的核心特点是 API 定义驱动开发:开发者可以通过 .api 文件描述 HTTP 接口,并使用 goctl 自动生成路由、控制器、逻辑层及相关代码;对于 RPC 服务,则可通过 Protocol Buffers 定义接口并生成代码,减少重复劳动,统一项目结构。框架内置服务治理机制,能够降低分布式系统的开发与运维复杂度。
在架构设计上,go-zero 强调分层组织、依赖隔离和工程规范,适合构建用户服务、订单系统及其他业务微服务。相比轻量级 Web 框架 Gin,go-zero 提供了更完整的微服务基础设施;但对于简单的单体应用,其整体约束和学习成本也相对更高。
参考资料与拓展阅读
- polarisxu, 关于 Go 语言微服务框架 Micro 的一些情况说明
- Micro, FAQ
Golang RabbitMQ
Golang RabbitMQ MQ 2021-06-18- 2014/07/11, RabbitMQ & AMQP
- 2015/02/12, Python RabbitMQ
- 2015/04/01, RabbitMQ 管理命令
- 2015/05/04, pika 01: 基础
- 2015/05/04, pika 02: BlockingConnection
- 2015/05/05, pika 03: SelectConnection
- 2015/05/06, pika 04: TornadoConnection
- 2016/02/12, Java RabbitMQ
- 2018/01/31, RabbitMQ 集群
- 2018/04/01, 面试题:RabbitMQ 相关
- 2018/10/02, pika: AsyncioConnection
- 2018/10/06, 使用 RabbitMQ 遇到的一个小问题
- 2019/01/12, 延迟队列
- 2020/10/03, 常见的消息队列
- 2021/06/18, Golang RabbitMQ
RabbitMQ 是啥就不说了,怎么安装部署也不说了,就记录一下 RabbitMQ 在 Golang 开发中的应用。
说明:采用 github.com/streadway/amqp 库。
func (ch *Channel) Publish(exchange, key string, mandatory, immediate bool, msg Publishing) error
func (ch *Channel) Consume(queue, consumer string, autoAck, exclusive, noLocal, noWait bool, args Table) (<-chan Delivery, error)
生产者
生产者基本流程
生产者:连接
amqp.Dial->amqp.Connectionamqp.Connection.Channel->amqp.Channel
conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
if err != nil {
log.Fatalf("Failed to connect to RabbitMQ: %s", err)
}
ch, err := conn.Channel()
if err != nil {
log.Fatalf("Failed to open a channel: %s", err)
}
生产者:配置(可选)
事先把 MQ 配好就行,但从稳妥起见,还是在连接时加上比较好。
amqp.Channel.QueueDeclareamqp.Channel.ExchangeDeclareamqp.Channel.QueueBind
q, err := ch.QueueDeclare(
"hello", // 队列名称
true, // 持久化
false, // 自动删除
false, // 独占
false, // 等待服务器回应
nil, // 额外参数
)
if err != nil {
log.Fatalf("Failed to declare a queue: %s", err)
}
生产者:发送
amqp.Channel.Publish
err = ch.Publish(
"", // exchange
q.Name, // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
ContentType: "text/plain",
Body: []byte("hello world"),
})
if err != nil {
log.Fatalf("Failed to publish a message: %s", err)
}
生产者:收尾
amqp.Connection.Closeamqp.Channel.Close
消费者
消费者基本流程
和生产者基本一致。只是调用的的是 chan.Consume 而不是 chan.Publish。
然后就是配置阶段,消费者只用关心队列在不在。
package main
import (
"context"
"encoding/json"
"log"
"time"
"github.com/streadway/amqp"
)
// Consumer RabbitMQ 消费者
type Consumer struct {
conn *amqp.Connection
channel *amqp.Channel
queue string
}
// NewConsumer 创建消费者
func NewConsumer(conn *amqp.Connection, ch *amqp.Channel, queueName string) (*Consumer, error) {
// 声明队列
_, err = DeclareQueue(ch, queueName)
if err != nil {
return nil, err
}
return &Consumer{
conn: conn,
channel: ch,
queue: queueName,
}, nil
}
// Consume 消费消息
func (c *Consumer) Consume(ctx context.Context, workerID int) error {
// 设置 QoS
err := c.channel.Qos(
1, // prefetch count
0, // prefetch size
false, // global
)
if err != nil {
return err
}
// 开始消费
msgs, err := c.channel.Consume(
c.queue, // queue
"", // consumer
false, // auto-ack
false, // exclusive
false, // no-local
false, // no-wait
nil, // args
)
if err != nil {
return err
}
log.Printf("消费者 %d 已启动,等待消息...", workerID)
for {
select {
case <-ctx.Done():
log.Printf("消费者 %d 停止", workerID)
return nil
case msg, ok := <-msgs:
if !ok {
log.Printf("消费者 %d 消息通道关闭", workerID)
return nil
}
// 处理消息
var message Message
if err := json.Unmarshal(msg.Body, &message); err != nil {
log.Printf("解析消息失败: %v", err)
msg.Nack(false, false) // 拒绝消息,不重新入队
continue
}
// 模拟处理时间
log.Printf("消费者 %d 处理消息: %+v", workerID, message)
time.Sleep(1 * time.Second)
// 确认消息
if err := msg.Ack(false); err != nil {
log.Printf("确认消息失败: %v", err)
}
}
}
}
// Close 关闭连接
func (c *Consumer) Close() {
if c.channel != nil {
c.channel.Close()
}
if c.conn != nil {
c.conn.Close()
}
}
复习:Exchange Types
- Fanout: 忽略 routingKey / bindingKey,将消息广播给所有绑定队列
- Header: 忽略 routingKey / bindingKey,根据消息和队列绑定时指定的 headers 匹配
- 支持精准匹配、数字匹配
- 匹配规则:x-match = all(默认)/ any
- 据说性能很差,没有使用过,官方文档都没有提供代码示例
- Direct: routingKey = bindingKey
- Topic: routingKey 模糊匹配 bindingKey(
*表示一个单词,#表示若干个单词)
默认 Exchange
- 名称:空字符串
- 类型:Direct
- 特性:所有已声明的队列都会隐式绑定(implicit route)到默认 Exchange,bindingKey queue.Name
所以 routingKey quene.Name 就可以将消息发送给对应的队列
参考资料与拓展阅读
Golang Redis
Golang Redis 2021-06-05package main
import (
"log"
"time"
"github.com/go-redis/redis"
)
func main() {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "",
DB: 0,
})
var err error
// 使用 Get/Set/Del =====================================
err = client.Set("key", "value", 0).Err()
if err != nil {
panic(err)
}
val, err := client.Get("key").Result()
if err != nil {
panic(err)
}
log.Println("key", val)
err = client.Del("key").Err()
if err != nil {
panic(err)
}
// 使用 Pipeline ========================================
pipeline := client.Pipeline()
pipeline.Set("key1", "value1", time.Minute*5)
pipeline.Set("key2", "value2", time.Minute*5)
pipeline.Set("key3", "value3", time.Minute*5)
_, err = pipeline.Exec()
if err != nil {
panic(err)
}
pipeline.Get("key1")
pipeline.Get("key2")
pipeline.Get("key3")
vals, err := pipeline.Exec()
if err != nil {
panic(err)
}
val1, _ := vals[0].(*redis.StringCmd).Result()
val2, _ := vals[1].(*redis.StringCmd).Result()
val3, _ := vals[2].(*redis.StringCmd).Result()
log.Println("key1", val1)
log.Println("key2", val2)
log.Println("key3", val3)
pipeline.Del("key1", "key2", "key3")
_, err = pipeline.Exec()
if err != nil {
panic(err)
}
}
package main
import (
"log"
"github.com/go-redis/redis"
)
func main() {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "",
DB: 0,
})
log.Println(client)
var err error
var items []string
// List ===============================================
{
err = client.RPush("mylist", "item1", "item2", "item3").Err()
if err != nil {
panic(err)
}
listLen, err := client.LLen("mylist").Result()
if err != nil {
panic(err)
}
log.Println("Length of mylist:", listLen)
items, err = client.LRange("mylist", 0, -1).Result()
if err != nil {
panic(err)
}
log.Println("===== Items in mylist:", items)
}
// Hash ===============================================
{
err = client.HSet("myhash", "field1", "value1").Err()
if err != nil {
panic(err)
}
value1, err := client.HGet("myhash", "field1").Result()
if err != nil {
panic(err)
}
log.Println("Value of field1:", value1)
allFields, err := client.HGetAll("myhash").Result()
if err != nil {
panic(err)
}
log.Println("===== All fields in myhash:", allFields)
}
// Set ================================================
{
err = client.SAdd("myset", "item1", "item2", "item3").Err()
if err != nil {
panic(err)
}
setLen, err := client.SCard("myset").Result()
if err != nil {
panic(err)
}
log.Println("Length of myset:", setLen)
items, err = client.SMembers("myset").Result()
if err != nil {
panic(err)
}
log.Println("===== Items in myset:", items)
}
// ZSet ===============================================
{
err = client.ZAdd("myzset", redis.Z{Score: 1.0, Member: "one"}, redis.Z{Score: 2.0, Member: "two"}).Err()
if err != nil {
panic(err)
}
setLen, err := client.ZCard("myzset").Result()
if err != nil {
panic(err)
}
log.Println("Length of myzset:", setLen)
items, err = client.ZRange("myzset", 0, -1).Result()
if err != nil {
panic(err)
}
log.Println("===== Items in myzset:", items)
}
}
哨兵
这样理论上来说,肯定会有性能损耗,毕竟增加了和哨兵的通信。
具体能差多少,还得实验。
package main
import (
"fmt"
"github.com/go-redis/redis/v8"
)
func main() {
failoverClient := redis.NewFailoverClient(&redis.FailoverOptions{
SentinelAddrs: []string{"sentinel1:26379", "sentinel2:26379", "sentinel3:26379"},
MasterName: "mymaster",
})
pong, err := failoverClient.Ping().Result()
if err != nil {
panic(err)
}
fmt.Println(pong)
}
集群
package main
import (
"fmt"
"github.com/go-redis/redis/v8"
)
func main() {
clusterClient := redis.NewClusterClient(&redis.ClusterOptions{
Addrs: []string{"redis1:6379", "redis2:6379", "redis3:6379"},
})
pong, err := clusterClient.Ping().Result()
if err != nil {
panic(err)
}
fmt.Println(pong)
}
Golang MySQL
Golang DB MySQL 2021-06-04测试表:
CREATE TABLE `users` (
`id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
`username` VARCHAR(50) NOT NULL COLLATE 'utf8mb4_unicode_ci',
`password` VARCHAR(100) NOT NULL COLLATE 'utf8mb4_unicode_ci',
`nickname` VARCHAR(50) NOT NULL COLLATE 'utf8mb4_unicode_ci',
`email` VARCHAR(100) NOT NULL DEFAULT '' COLLATE 'utf8mb4_unicode_ci',
`birthday` VARCHAR(10) NOT NULL DEFAULT '0000-00-00' COLLATE 'utf8mb4_unicode_ci',
`age` TINYINT(3) UNSIGNED NOT NULL DEFAULT '0',
`level` TINYINT(3) NOT NULL DEFAULT '0',
`disabled` TINYINT(1) NOT NULL DEFAULT '0',
`created_at` DATETIME NOT NULL DEFAULT current_timestamp(),
`updated_at` DATETIME NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `username` (`username`) USING BTREE
)
COLLATE='utf8mb4_unicode_ci'
ENGINE=InnoDB;
连接
package main
import (
"database/sql"
"fmt"
"time"
_ "github.com/go-sql-driver/mysql"
)
var db *sql.DB //全局变量client
func initMySQL() (err error) {
dsn := "root:123456@tcp(127.0.0.1:3306)/test"
db, err = sql.Open("mysql", dsn)
if err != nil {
panic(err)
}
err = db.Ping() //检测是否连接成功
if err != nil {
return
}
db.SetMaxOpenConns(200) //最大连接数
db.SetMaxIdleConns(10) //连接池里最大空闲连接数。必须要比maxOpenConns小
db.SetConnMaxLifetime(time.Second * 10) //最大存活保持时间
db.SetConnMaxIdleTime(time.Second * 10) //最大空闲保持时间
return
}
func main() {
if err := initMySQL(); err != nil {
fmt.Printf("connect to db failed,err:%v\n", err)
} else {
fmt.Println("connect to db success")
}
sqlStr := "SELECT id, name FROM sys_user WHERE id=?"
var u user
//非常重要:确保QueryRow之后调用Scan方法,否则持有的数据库链接不会被释放
err := db.QueryRow(sqlStr, 1).Scan(&u.id, &u.name)
if err != nil {
fmt.Printf("scan failed, err: %v\n", err)
return
}
fmt.Printf("id:%d,name:%s,age:%d\n", u.id, u.name)
defer db.Close()
}
//user结构体
type user struct {
id int
name string
}
Insert 增
Update 改
Delete 删
Select 查
Go interface
Golang 2021-06-02不像我们常见的一些语言,实现接口需要显式声明,比如 PHP:
interface Animal {
public function move();
public function makeSound();
}
class Dog implements Animal {
public function move() {
echo "Dog is moving\n";
}
public function makeSound() {
echo "Woof\n";
}
}
Go 不需要声明,说到不如做到,实现了所有接口方法就行了。
PS:我还是觉得写出来比较好一些,阅读代码的时候更加一目了然,也没有什么副作用。
示例
package main
import "fmt"
type Animal interface {
move() string
makeSound() string
}
type Dog struct {
name string
}
func (d Dog) move() string {
return fmt.Sprintf("%s is running", d.name)
}
func (d Dog) makeSound() string {
return "woof"
}
func main() {
dog := Dog{name: "Fido"}
// 判断接口实现关系
_, ok := interface{}(dog).(Animal)
if ok {
fmt.Printf("%T is Animal\n", dog)
} else {
fmt.Printf("%T is NOT Animal\n", dog)
}
fmt.Println(dog.move())
fmt.Println(dog.makeSound())
}
interface{}
interface{}says nothing.
Go 谚语第六条是什么意思?
我的理解:
interface{} 可以表示任意类型,有时使用起来会很方便。
但是必须注意这意味着对类型没有任何约束,无论从程序的严谨度还是代码可读性上讲,都是有害的。
如何可以的话,编码中应当尽量采用范围小一些的接口,就比如到处可见的 io.Writer 接口,它有各类实现:
bytes.Bufferbufio.Writeros.Filecompress/gzip.Writercrypto/cipher.StreamWriterencoding/csv.Writernet/http.ResponseWriterarchive/zip.Writerimage/png.Encoder
Golang JSON
Golang JSON 2021-06-02Golang 有一个 encoding/json 标准库,在多数情况下已经够用了。
注意:因为 Golang 是一种静态类型的语言,所以解析 JSON 字符串必须了解里面的数据结构。
如果是用惯了 JS、Python、PHP 等动态语言的话,到这里会有些郁闷,怎么解析一个 JSON 还这么复杂。
Gron 的设计
Golang 定时任务 2021-05-302021/08/23,Golang 定时任务 是讲通过 Golang 原生的 time.Ticker 实现定时任务,本文介绍的是通过第三方库 robfig/cron 实现定时任务。
概述
- 代码:robfig/cron
- 文档: https://godoc.org/github.com/robfig/cron
标准 Cron 表达式 分成 5 段:分 minutes、时 hours、日 day of month、月 month、周 day of week。
robfig/cron v2 默认支持 6 个字段(包括秒 seconds),从 v3 开始又回到默认 5 个字段(需要做以下显式声明:cron.New(cron.WithSeconds()))。
type SpecSchedule struct {
Second, Minute, Hour, Dom, Month, Dow uint64
}
使用
// Seconds field, required
cron.New(cron.WithSeconds())
// Seconds field, optional
cron.New(cron.WithParser(cron.NewParser(
cron.SecondOptional | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor,
)))
c := cron.New()
c.AddFunc("0 30 * * * *", func() { fmt.Println("Every hour on the half hour") })
c.AddFunc("@hourly", func() { fmt.Println("Every hour") })
c.AddFunc("@every 1h30m", func() { fmt.Println("Every hour thirty") })
c.Start()
..
// Funcs are invoked in their own goroutine, asynchronously.
...
// Funcs may also be added to a running Cron
c.AddFunc("@daily", func() { fmt.Println("Every day") })
..
// Inspect the cron job entries' next and previous run times.
inspect(c.Entries())
..
c.Stop() // Stop the scheduler (does not stop any jobs already running).
Field name | Mandatory? | Allowed values | Allowed special characters
---------- | ---------- | -------------- | --------------------------
Seconds | Yes | 0-59 | * / , -
Minutes | Yes | 0-59 | * / , -
Hours | Yes | 0-23 | * / , -
Day of month | Yes | 1-31 | * / , - ?
Month | Yes | 1-12 or JAN-DEC | * / , -
Day of week | Yes | 0-6 or SUN-SAT | * / , - ?
Entry | Description | Equivalent To
----- | ----------- | -------------
@yearly (or @annually) | Run once a year, midnight, Jan. 1st | 0 0 0 1 1 *
@monthly | Run once a month, midnight, first of month | 0 0 0 1 * *
@weekly | Run once a week, midnight between Sat/Sun | 0 0 0 * * 0
@daily (or @midnight) | Run once a day, midnight | 0 0 0 * * *
@hourly | Run once an hour, beginning of hour | 0 0 * * * *
Golang 时间处理
Golang 2021-05-21主要是 time 包(2021/05/21,Golang time 包)。
time.Time时间,精确到纳秒time.Location时区time.Duration时间间隔,精确到纳秒,[-292.47 years, 292.47 years]
(1 << 63) / 1_000_000_000 / 3600 / 24 / 365
292.471208677536
src/time/time.go:type Time struct {
src/time/time.go- wall uint64 // 秒 wall time seconds
src/time/time.go- ext int64 // 毫秒 wall time nanoseconds
src/time/time.go- loc *Location // 时区
src/time/time.go-}
src/time/zoneinfo.go:type Location struct {
src/time/zoneinfo.go- name string
src/time/zoneinfo.go- zone []zone
src/time/zoneinfo.go- tx []zoneTrans
src/time/zoneinfo.go- extend string
src/time/zoneinfo.go- cacheStart int64
src/time/zoneinfo.go- cacheEnd int64
src/time/zoneinfo.go- cacheZone *zone
src/time/zoneinfo.go-}
src/time/zoneinfo.go:type zone struct {
src/time/zoneinfo.go- name string // abbreviated name, "CET"
src/time/zoneinfo.go- offset int // seconds east of UTC
src/time/zoneinfo.go- isDST bool // is this zone Daylight Savings Time?
src/time/zoneinfo.go-}
src/time/zoneinfo.go-type zoneTrans struct {
src/time/zoneinfo.go- when int64 // transition time, in seconds since 1970 GMT
src/time/zoneinfo.go- index uint8 // the index of the zone that goes into effect at that time
src/time/zoneinfo.go- isstd, isutc bool // ignored - no idea what these mean
src/time/zoneinfo.go-}
var UTC *Location = &utcLoc
var utcLoc = Location{name: "UTC"}
var Local *Location = &localLoc
var localLoc Location
src/time/time.go:type Duration int64
基本用法
time.Now() // time.Time
// type Month int
// const (
// January Month = 1 + iota
// February
// March
// April
// May
// June
// July
// August
// September
// October
// November
// December
// )
// var Local *Location = &localLoc
func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time // 组装 Time
// Time -> 时间戳
time.Now().Unix() // int64
time.Now().UnixMilli() // int64 毫秒
time.Now().UnixMicro() // int64 微秒
time.Now().UnixNano() // int64 纳秒
func Unix(sec int64, nsec int64) Time // 时间戳 -> Time
time.Now().Format("2006-01-02 15:04:05") // Time -> timestr
timeObj, erro := time.Parse("2006-01-02 15:04:05", timestr) // timestr -> Time
// 特别注意:time.Parse 是按照 UTC 时区解析
timeObj, erro := time.ParseInLocation("2006-01-02 15:04:05", timeStr, time.Local)
间隔计算
func (t Time) Truncate(d Duration) Time
func (t Time) Round(d Duration) Time
func (d Duration) Truncate(m Duration) Duration
func (d Duration) Round(m Duration) Duration
func (t Time) Add(d Duration) Time // Time 相加
func (t Time) Sub(u Time) Duration // Time 相减
func Since(t Time) Duration // Now - t
func Until(t Time) Duration // t - Now
time.Now().Truncate(时间)
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println("Hello, 世界")
now := time.Date(2021, 5, 21, 15, 46, 47, 0, time.Local)
fmt.Println(now)
// d := time.Hour
d := time.Duration(3000_000_000_000)
fmt.Println(now.Truncate(d))
fmt.Println(now.Round(d))
}
// 2021-05-21 15:46:47 +0000 UTC
// 2021-05-21 15:00:00 +0000 UTC
// 2021-05-21 15:50:00 +0000 UTC
时区
使用 Go 语言开发 Python 拓展
Golang Python PythonExt 2021-05-15Python 有一个好搭档就是 C/C,Python 提供生产力,C/C 则负责效率。
这篇文章探讨 Python + Go 混合开发的可能性。
Gin 框架自学: 实战 [编辑中]
GinNotes Golang GORM Gin 2021-05-07:) 本文正在编辑中,暂时不提供浏览...
Gin 框架自学: ORM [编辑中]
GinNotes Golang GORM Gin 2021-05-06:) 本文正在编辑中,暂时不提供浏览...
Gin 框架自学: 基础
GinNotes Golang Gin 2021-05-06先列一下目前最火的几个 Go 语言框架:
- gin
- beego 国人开发
- iris The fastest HTTP/2 Go Web Framework.
自称是 ExpressJS 和 Laravel 的继承者。
- echo High performance, minimalist Go web framework
- go-micro Microservice framework for Go
- fiber
- kratos A Go framework for microservices. B 站出品
- revel/revel
- go-zero 国人开发(七牛)
- martini Classy web framework for Go
- GoFrame Classy web framework for Go 国人开发
Gin

Gin 相比 Beego 非常轻量级,不带 ORM,不支持 Session,正则路由都不支持,需要自行实现。
最新版本 56 个 文件, 算上注释,大概七千行代码。
$ find . -name "*.go" -not -path "*_test.go" | cat | wc -l
56
$ find . -name "*.go" -not -path "*_test.go" | xargs cat | wc -l
6910
| Tag | CreatedAt | ReleasedAt |
|---|---|---|
| v1.9.0 | 2023-02-21 | 2023-02-21 |
| v1.8.2 | 2022-12-22 | 2022-12-22 |
| v1.8.1 | 2022-06-06 | 2022-06-06 |
| v1.8.0 | 2022-05-30 | 2022-05-30 |
| v1.7.7 | 2021-11-24 | 2021-11-24 |
| v1.7.6 | 2021-08-03 | 2021-11-23 |
| v1.7.4 | 2021-08-03 | 2021-08-15 |
| v1.7.3 | 2021-08-03 | 2021-08-03 |
| v1.7.2 | 2021-05-21 | 2021-05-21 |
| v1.7.1 | 2021-04-08 | 2021-04-08 |
| v1.7.0 | 2021-04-08 | 2021-04-08 |
| v1.6.3 | 2020-05-03 | 2020-05-03 |
| v1.6.2 | 2020-03-27 | 2020-03-27 |
| v1.6.1 | 2020-03-23 | 2020-03-23 |
| v1.6.0 | 2020-03-22 | 2020-03-22 |
| v1.5.0 | 2019-11-24 | 2019-11-28 |
| v1.4.0 | 2019-05-07 | 2019-05-08 |
| v1.3.0 | 2018-08-14 | 2018-08-14 |
| v1.2 | 2017-07-02 | 2017-07-02 |
| v1.1.4 | 2016-12-04 | 2016-12-05 |
| v1.1.3 | 2016-12-03 | 2016-12-04 |
HTTP 参数
// c: *gin.Context
// func (c *gin.Context) {
// balabala...
// }
c.Request.URL.Query()
c.Param(key string) string // 路径参数
c.Params.ByName(key)
c.Query(key string) string // 查询参数
c.Request.URL.Query().Get(key)
c.GetQuery(key)
c.QueryMap(key string) map[string][]string
c.GetQueryMap(key)
c.QueryArray(key string) []string
c.GetQuery(key string) (string, bool)
c.GetQueryArray(key) 的第 0 个元素
c.GetQueryMap(key string) (map[string]string, bool)
c.GetQueryArray(key string) (values []string, ok bool)
c.PostForm(key string) string
c.PostFormMap(key string) map[string][]string
c.PostFormArray(key string) []string
c.GetPostForm(key string) (string, bool)
c.GetPostFormMap(key string) (map[string]string, bool)
c.GetPostFormArray(key string) (values []string, ok bool)
c.FormFile(key string) (*multipart.FileHeader, error)
c.DefaultQuery(key string, defaultValue string) string
c.DefaultPostForm(key string, defaultValue string) string
- 2021/05/06, Gin 框架自学: 基础
- 2021/05/06, Gin 框架自学: ORM
- 2021/05/07, Gin 框架自学: 实战
- 2021/08/17, Gin 源码阅读
- 2022/04/03, Gin + Vue3 (ElementPlus) 开发一个通用管理后台
快速启动
package main
import (
"io"
"net/http"
"os"
"path/filepath"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
// 处理 GET 请求中的 URL 参数
r.GET("/hello", func(c *gin.Context) {
name := c.Query("name")
c.String(http.StatusOK, "Hello %s!", name)
})
// 处理带路径参数的 GET 请求
r.GET("/users/:id", func(c *gin.Context) {
id := c.Param("id")
c.String(http.StatusOK, "User ID: %s", id)
})
// 处理 POST 请求中的 JSON 请求体
r.POST("/data", func(c *gin.Context) {
var json struct {
Data string `json:"data"`
}
c.BindJSON(&json)
c.JSON(http.StatusOK, gin.H{"message": "Received data: " + json.Data})
})
// 处理文件上传
r.POST("/upload", func(c *gin.Context) {
file, err := c.FormFile("file")
if err != nil {
c.String(http.StatusBadRequest, "File upload failed: %s", err.Error())
return
}
// 将上传的文件保存到服务器上
dst := filepath.Join("./uploads", file.Filename)
if err := c.SaveUploadedFile(file, dst); err != nil {
c.String(http.StatusInternalServerError, "File save failed: %s", err.Error())
return
}
c.String(http.StatusOK, "File uploaded successfully")
})
// 处理返回文件
r.GET("/download", func(c *gin.Context) {
filename := "example.txt"
filepath := "./downloads/" + filename
// 打开文件
file, err := os.Open(filepath)
if err != nil {
c.String(http.StatusInternalServerError, "Failed to open file: %s", err.Error())
return
}
defer file.Close()
// 设置响应头
c.Header("Content-Disposition", "attachment; filename="+filename)
c.Header("Content-Type", "application/octet-stream")
c.Header("Content-Transfer-Encoding", "binary")
// 将文件内容写入响应主体
_, err = io.Copy(c.Writer, file)
if err != nil {
c.String(http.StatusInternalServerError, "Failed to write file: %s", err.Error())
}
})
r.Run(":8080")
}
路由
设置路由不存在的处理方法:
r.NoRoute(func(c *gin.Context) {
c.JSON(404, gin.H{"message": "page not found"})
})
限制请求大小:
r.MaxMultipartMemory = 10 << 20 // 10MB
// "github.com/gin-contrib/size"
r.Use(size.Check(size.MB * 10))
r.Use(requestSizeLimitMiddleware(10 << 20))
func requestSizeLimitMiddleware(maxSize int64) gin.HandlerFunc {
return func(c *gin.Context) {
if c.Request.ContentLength > maxSize {
c.AbortWithStatusJSON(413, gin.H{"message": "request entity too large"})
return
}
c.Next()
}
}
Golang 自动过期 Map
Golang 2021-04-26type ExpiringMap struct {
m sync.Map
expiry time.Duration
}
func (e *ExpiringMap) set(key, value interface{}) {
e.m.Store(key, value)
go func() {
time.Sleep(e.expiry)
e.m.Delete(key)
}()
}
改进:定时清理
package main
import (
"sync"
"time"
)
type Item struct {
value interface{}
expiration int64
}
type ExpiringMap struct {
m sync.Mutex
items map[string]Item
timeout time.Duration
}
func NewExpiringMap(timeout time.Duration) *ExpiringMap {
em := &ExpiringMap{
items: make(map[string]Item),
timeout: timeout,
}
go em.cleanup()
return em
}
func (em *ExpiringMap) Set(key string, value interface{}) {
em.m.Lock()
defer em.m.Unlock()
em.items[key] = Item{
value: value,
expiration: time.Now().Add(em.timeout).UnixNano(),
}
}
func (em *ExpiringMap) Get(key string) (interface{}, bool) {
em.m.Lock()
defer em.m.Unlock()
item, found := em.items[key]
if !found {
return nil, false
}
if time.Now().UnixNano() > item.expiration {
return nil, false
}
return item.value, true
}
func (em *ExpiringMap) Delete(key string) {
em.m.Lock()
defer em.m.Unlock()
delete(em.items, key)
}
func (em *ExpiringMap) deleteExpiredKeys() {
em.m.Lock()
defer em.m.Unlock()
now := time.Now().UnixNano()
for key, item := range em.items {
if now < item.expiration {
break
}
delete(em.items, key)
}
}
func (em *ExpiringMap) cleanup() {
for {
time.Sleep(em.timeout) // 阻塞协程
em.deleteExpiredKeys()
}
}
func main() {
em := NewExpiringMap(time.Second * 10)
time.Sleep(time.Second * 15)
_, ok := em.Get("key1")
if !ok {
println("key1 is deleted")
}
_, ok = em.Get("key2")
if !ok {
println("key2 is deleted")
}
}
fasthttp: 十倍速
Golang fasthttp 2021-04-26https://github.com/valyala/fasthttp
在高并发、短请求、简单 HTTP 服务等场景,fasthttp 通过对象复用、减少内存分配、避免部分抽象开销,可获得 5 倍甚至更高的吞吐提升(官方提供的压测数据)。
说 10 倍是有标题党嫌疑啦,主要是经常在网上看到文章说 fasthttp 快 10 倍之类。
| 场景 | net/http | fasthttp | 加速倍数 |
|---|---|---|---|
| GOMAXPROCS=1,1 Req/Conn | 15327 | 2733 | 5.61× |
| GOMAXPROCS=1,2 Req/Conn | 11533 | 2140 | 5.39× |
| GOMAXPROCS=1,10 Req/Conn | 8734 | 1550 | 5.63× |
| GOMAXPROCS=1,10K Req/Conn | 7151 | 1422 | 5.03× |
| GOMAXPROCS=4,1 Req/Conn | 4542 | 1494 | 3.04× |
| GOMAXPROCS=4,2 Req/Conn | 3559 | 963 | 3.69× |
| GOMAXPROCS=4,10 Req/Conn | 2707 | 522 | 5.18× |
| GOMAXPROCS=4,10K Req/Conn | 2179 | 451 | 4.83× |
需要注意的是,真实业务中,HTTP 框架只占总耗时很小一部分,甚至可以说忽略不计,通常还有 JSON 编解码、数据库、Redis、网络延迟、业务逻辑等开销更大一些。
一般来说,除非做了实际压测确认 HTTP 框架是瓶颈,切换 fasthttp 有明显收益,一律默认使用基于标准库的 HTTP 框架,毕竟还得考虑 API 兼容性和生态成本。
性能好的原因分析:
- 对象池复用:RequestCtx、Request、Response 等对象通过对象池循环使用,减少频繁创建和销毁,从而降低堆分配与 GC 压力。
- []byte 与 Buffer 复用:HTTP 解析尽量直接操作已有字节缓冲区,减少 string 转换、数据复制和临时对象创建,同时降低内存分配。
- Worker Pool:通过 worker pool 复用连接处理 goroutine,并控制并发规模,避免高并发下大量创建 goroutine,降低调度和资源开销。
- 减少抽象层:直接使用
RequestCtx处理请求和响应,减少net/http中间抽象及对象转换,为更激进的内存复用提供空间。 - 生命周期设计:RequestCtx、[]byte、Buffer 等资源只在请求生命周期内安全使用,结束后立即复用;用更严格的生命周期约束换取更低的内存分配。
标准库的目标不是追求极限 Benchmark,而是通用性、兼容性、稳定性和可维护性。激进的对象池、零拷贝会引入严格生命周期约束,增加 API 心智负担,并限制 HTTP/2、生态兼容等能力。
net/http 更倾向于提供长期稳定的基础设施,而不是为极端高 QPS 场景牺牲通用性。
fasthttp
package main
import (
"flag"
"fmt"
"log"
"github.com/valyala/fasthttp"
)
var (
addr = flag.String("addr", ":8080", "TCP address to listen to")
compress = flag.Bool("compress", false, "Whether to enable transparent response compression")
)
func main() {
flag.Parse()
h := requestHandler
if *compress {
h = fasthttp.CompressHandler(h)
}
if err := fasthttp.ListenAndServe(*addr, h); err != nil {
log.Fatalf("Error in ListenAndServe: %v", err)
}
}
func requestHandler(ctx *fasthttp.RequestCtx) {
fmt.Fprintf(ctx, "Hello, world!\n\n")
fmt.Fprintf(ctx, "Request method is %q\n", ctx.Method())
fmt.Fprintf(ctx, "RequestURI is %q\n", ctx.RequestURI())
fmt.Fprintf(ctx, "Requested path is %q\n", ctx.Path())
fmt.Fprintf(ctx, "Host is %q\n", ctx.Host())
fmt.Fprintf(ctx, "Query string is %q\n", ctx.QueryArgs())
fmt.Fprintf(ctx, "User-Agent is %q\n", ctx.UserAgent())
fmt.Fprintf(ctx, "Connection has been established at %s\n", ctx.ConnTime())
fmt.Fprintf(ctx, "Request has been started at %s\n", ctx.Time())
fmt.Fprintf(ctx, "Serial request number for the current connection is %d\n", ctx.ConnRequestNum())
fmt.Fprintf(ctx, "Your ip is %q\n\n", ctx.RemoteIP())
fmt.Fprintf(ctx, "Raw request is:\n---CUT---\n%s\n---CUT---", &ctx.Request)
ctx.SetContentType("text/plain; charset=utf8")
// Set arbitrary headers
ctx.Response.Header.Set("X-My-Header", "my-header-value")
// Set cookies
var c fasthttp.Cookie
c.SetKey("cookie-name")
c.SetValue("cookie-value")
ctx.Response.Header.SetCookie(&c)
}
r.Body->ctx.PostBody()r.URL.Path->ctx.Path()r.URL->ctx.URI()r.Method->ctx.Method()r.Header->ctx.Request.Headerr.Header.Get()->ctx.Request.Header.Peek()r.Host->ctx.Host()r.Form->ctx.QueryArgs()+ctx.PostArgs()r.PostForm->ctx.PostArgs()r.FormValue()->ctx.FormValue()r.FormFile()->ctx.FormFile()r.MultipartForm->ctx.MultipartForm()r.RemoteAddr->ctx.RemoteAddr()r.RequestURI->ctx.RequestURI()r.TLS->ctx.IsTLS()r.Cookie()->ctx.Request.Header.Cookie()r.Referer()->ctx.Referer()r.UserAgent()->ctx.UserAgent()w.Header()->ctx.Response.Headerw.Header().Set()->ctx.Response.Header.Set()w.Header().Set("Content-Type")->ctx.SetContentType()w.Header().Set("Set-Cookie")->ctx.Response.Header.SetCookie()w.Write()->ctx.Write(),ctx.SetBody(),ctx.SetBodyStream(),ctx.SetBodyStreamWriter()w.WriteHeader()->ctx.SetStatusCode()w.(http.Hijacker).Hijack()->ctx.Hijack()http.Error()->ctx.Error()http.FileServer()->fasthttp.FSHandler(),fasthttp.FShttp.ServeFile()->fasthttp.ServeFile()http.Redirect()->ctx.Redirect()http.NotFound()->ctx.NotFound()http.StripPrefix()->fasthttp.PathRewriteFunc
fasthttp/router
/user/{user}named/user/{user}_admin/user/{user?}optional/user/{name:[a-zA-Z]{5}}regex/user/{name?:[a-zA-Z]{5}}/user/{name:*}cache all
fasthttp/session
package main
import (
"log"
"time"
"github.com/fasthttp/session/v2"
"github.com/fasthttp/session/v2/providers/redis"
)
var serverSession *session.Session
func init() {
var provider session.Provider
var err error
encoder := session.MSGPEncode
decoder := session.MSGPDecode
provider, err = redis.New(redis.Config{
KeyPrefix: "session",
Addr: "127.0.0.1:6379",
PoolSize: 8,
IdleTimeout: 30 * time.Second,
})
if err != nil {
log.Fatal(err)
}
cfg := session.NewDefaultConfig()
cfg.EncodeFunc = encoder
cfg.DecodeFunc = decoder
serverSession = session.New(cfg)
if err = serverSession.SetProvider(provider); err != nil {
log.Fatal(err)
}
}
// 获取 SessionStore
store, err := serverSession.Get(ctx)
if err != nil {
ctx.Error(err.Error(), fasthttp.StatusInternalServerError)
return
}
defer func() {
if err := serverSession.Save(ctx, store); err != nil {
ctx.Error(err.Error(), fasthttp.StatusInternalServerError)
}
}()
// Set
store.Set("foo", "bar")
// Get
val := store.Get("foo")
if val == nil {
// ...
}
store.Delete(key)
store.Set(bytesKey)
val := store.GetBytes(bytesKey)
store.DeleteBytes(bytesKey)
data := store.GetAll() // Dict
data := store.Ptr() // *Dict
store.Flush()
store.Reset()
// Session ID,默认 sessionid
id := store.GetSessionID()
store.SetSessionID(bytesID)
// Session 有效期
changed := store.HasExpirationChanged()
duration := store.GetExpiration()
err := store.SetExpiration(duration)
savsgio/atreugo
构建与 fasthttp 和 fasthttp/router 之上的 HTTP 框架,做了一些简单的封装工作。
提供了几个示例。
基础用法:
package main
import (
"github.com/savsgio/atreugo/v11"
)
func main() {
config := atreugo.Config{
Addr: "0.0.0.0:8000",
}
server := atreugo.New(config)
server.GET("/", func(ctx *atreugo.RequestCtx) error {
return ctx.TextResponse("Hello World")
})
server.GET("/echo/{path:*}", func(ctx *atreugo.RequestCtx) error {
return ctx.TextResponse("Echo message: " + ctx.UserValue("path").(string))
})
v1 := server.NewGroupPath("/v1")
v1.GET("/", func(ctx *atreugo.RequestCtx) error {
return ctx.TextResponse("Hello V1 Group")
})
if err := server.ListenAndServe(); err != nil {
panic(err)
}
}
Golang: possible resource leak,'defer' is called in the 'for' loop
Golang 2021-04-01类似代码:
for _, f := range files {
fp, err := os.Open(f)
if err != nil {
panic(err)
}
defer fp.Close()
// do something
}
Goland 提示:possible resource leak,'defer' is called in the 'for' loop
defer 是在最后函数退出时执行,但是变量已经经过循环覆盖,可能会导致内存泄漏。
似乎 Golang 的 defer 还是不够聪明。
换种写法:
for _, f := range files {
func () {
fp, err := os.Open(f)
if err != nil {
panic(err)
}
defer fp.Close()
// do something
}()
}
Golang ORM 框架
Golang 2021-03-30- GORM
- ent
- Xorm 转到Gitea
- Bun
- Reform
- GoRose
GitHub 搜索结果
- go-gorm/gorm
The fantastic ORM library for Golang, aims to be developer friendly - ent/ent
An entity framework for Go - geektutu/7days-golang
7 days golang programs from scratch (web framework Gee, distributed cache GeeCache, object relational mapping ORM framework GeeORM, rpc framework GeeRPC etc) 7 天用 Go 动手写/从零实现系列 - gogf/gf
GoFrame is a modular, powerful, high-performance and enterprise-class application development framework of Golang. - sqlc-dev/sqlc
Generate type-safe code from SQL - go-xorm/xorm
Simple and Powerful ORM for Go, support mysql,postgres,tidb,sqlite3,mssql,oracle, Moved to https://gitea.com/xorm/xorm - volatiletech/sqlboiler
Generate a Go ORM tailored to your database schema. - go-pg/pg
Golang ORM with focus on PostgreSQL features and performance - go-gorp/gorp
Go Relational Persistence - an ORM-ish library for Go - xo/xo
Command line tool to generate idiomatic Go code for SQL databases supporting PostgreSQL, MySQL, SQLite, Oracle, and Microsoft SQL Server - upper/db
Data access layer for PostgreSQL, CockroachDB, MySQL, SQLite and MongoDB with ORM-like features. - uptrace/bun
SQL-first Golang ORM - xxjwxc/gormt
database to golang struct - steebchen/prisma-client-go
Prisma Client Go is an auto-generated and fully type-safe database client - xormplus/xorm
xorm 是一个简单而强大的 Go 语言 ORM 库,通过它可以使数据库操作非常简便。本库是基于原版 xorm 的定制增强版本,为 xorm 提供类似 ibatis 的配置文件及动态 SQL 支持,支持 AcitveRecord 操作 - go-reform/reform
A better ORM for Go, based on non-empty interfaces and code generation. - gobuffalo/pop
A Tasty Treat For All Your Database Needs - bobohume/gonet
go 分布式服务器,基于内存 mmo - unionj-cloud/go-doudou
go-doudou(doudou pronounce /dəudəu/)is OpenAPI 3.0 (for REST) spec and Protobuf v3 (for grpc) based lightweight microservice framework. It supports monolith service application as well. - gohouse/gorose
GoRose(go orm), a mini database ORM for golang, which inspired by the famous php framwork laravle's eloquent. It will be friendly for php developer and python or ruby developer. Currently provides six major database drivers: mysql,sqlite3,postgres,oracle,mssql, Clickhouse. - huandu/go-sqlbuilder
A flexible and powerful SQL string builder library plus a zero-config ORM.
Golang 入门项目 httpbin 总结
Golang 2021-03-29httpbin 是我练手的一个非常简单的小项目,功能就是:
1. HTTP POST 请求 (POST /) 提交一个字符串,服务器返回一个 ID。
1. HTTP GET 请求 (GET /xxxx),返回 ID 对应的字符串。