GoByExample简单应用
Go 是一种开源编程语言
Go 是一种开源编程语言,旨在构建可扩展、安全可靠的软件。请阅读官方文档以了解更多信息。
Go by Example 是使用带注释的示例程序对 Go 的动手实践介绍。查看第一个例子或浏览下面的完整列表。
除非另有说明,否则此处的示例假定最新的主要版本 Go,并且可能会使用新的语言功能。如果出现问题,请尝试升级到最新版本。
Go语言的实用示例的编译
以下是关于Go语言的实用示例的编译和运行方法,涵盖基础语法、并发、网络、测试等核心内容:
获取源码
从官方仓库克隆或下载示例代码:
git clone https://github.com/mmcgrana/gobyexample
cd gobyexample
单文件编译
直接运行单个示例(如hello-world.go):
go run examples/hello-world/hello-world.go
生成可执行文件:
go build examples/hello-world/hello-world.go
./hello-world
批量编译
使用Makefile自动化编译:
make
该命令会编译examples目录下的所有示例程序
特殊示例处理
需要附加参数的示例(如命令行参数):
go run examples/command-line-arguments/command-line-arguments.go a b c
需要外部依赖的示例(如HTTP服务):
go get github.com/gorilla/mux
go run examples/json/json.go
测试运行
针对包含测试文件的示例:
go test examples/testing/testing_test.go
跨平台编译
生成Linux可执行文件:
GOOS=linux GOARCH=amd64 go build examples/hello-world/hello-world.go
生成Windows可执行文件:
GOOS=windows GOARCH=amd64 go build examples/hello-world/hello-world.go
容器化运行
使用Docker容器隔离环境:
docker build -t gobyexample .
docker run -it gobyexample /bin/bash
以下是一些当前流行的Go框架及其常见用例示例。这些框架覆盖了Web开发、微服务、数据库、测试等多个领域,每个类别提供多个示例代码片段或场景说明。
Go语言网络与Web框架
前置准备
F:\Program Files\Go\bin>go version
go version go1.24.2 windows/amd64
1. Gin
轻量级Web框架,适合API开发。
package main
import "github.com/gin-gonic/gin"
func main() {r := gin.Default()r.GET("/ping", func(c *gin.Context) {c.JSON(200, gin.H{"message": "pong"})})r.Run() // 默认监听 :8080
}
2. Echo
高性能Web框架,支持中间件。
package main
import "github.com/labstack/echo/v4"
func main() {e := echo.New()e.GET("/", func(c echo.Context) error {return c.String(200, "Hello, Echo!")})e.Start(":8080")
}
3. Fiber
受Express启发的框架,强调低内存占用。
package main
import "github.com/gofiber/fiber/v2"
func main() {app := fiber.New()app.Get("/", func(c *fiber.Ctx) error {return c.SendString("Hello, Fiber!")})app.Listen(":3000")
}
微服务框架
4. Go kit
构建微服务的工具集。
package main
import ("context""github.com/go-kit/kit/endpoint"
)
func makeEndpoint(svc Service) endpoint.Endpoint {return func(ctx context.Context, request interface{}) (interface{}, error) {req := request.(string)return svc.Upper(req), nil}
}
5. Micro
分布式系统开发框架。
service := micro.NewService(micro.Name("greeter"),
)
service.Init()
service.Run()
数据库与ORM
6. GORM
流行的ORM库。
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
if err != nil {panic("failed to connect database")
}
db.AutoMigrate(&Product{})
db.Create(&Product{Code: "D42", Price: 100})
7. Ent
实体框架,代码生成驱动。
client, err := ent.Open("sqlite3", "file:ent?mode=memory&cache=shared&_fk=1")
if err != nil {log.Fatalf("failed opening connection: %v", err)
}
defer client.Close()
ctx := context.Background()
if err := client.Schema.Create(ctx); err != nil {log.Fatalf("failed creating schema resources: %v", err)
}
实时通信
8. Melody
WebSocket框架。
m := melody.New()
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {m.HandleRequest(w, r)
})
m.HandleMessage(func(s *melody.Session, msg []byte) {m.Broadcast(msg)
})
http.ListenAndServe(":5000", nil)
测试与Mock
9. Testify
断言和Mock工具。
assert.Equal(t, 123, 123, "they should be equal")
mock.On("DoSomething", 123).Return(true, nil)
10. GoMock
接口Mock生成。
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mock := NewMockExample(ctrl)
mock.EXPECT().SomeMethod().Return(true)
其他工具类框架
11. Cobra
CLI应用构建。
cmd := &cobra.Command{Use: "echo",Short: "Echo anything",Run: func(cmd *cobra.Command, args []string) {fmt.Println(args)},
}
cmd.Execute()
12. Viper
配置管理。
viper.SetConfigName("config")
viper.AddConfigPath(".")
viper.ReadInConfig()
viper.GetString("database.url")
以上仅为部分示例,完整100例需结合具体场景(如日志库、缓存、任务队列等)展开。实际应用时需根据项目需求选择框架,并参考官方文档调整细节。