Golang Goal框架实战教程
Goal是一个轻量级的Go语言Web框架,专注于高性能和简洁API设计。以下是Goal框架的核心功能和使用方法:
1. 安装Goal框架
go get github.com/goal-web/application
2. 基础应用搭建
package main
import (
"github.com/goal-web/application"
"github.com/goal-web/router"
"net/http"
)
func main() {
// 创建应用实例
app := application.NewApp()
// 获取路由实例
router := app.Get("router").(*router.Router)
// 定义路由
router.Get("/", func(writer http.ResponseWriter, request *http.Request) {
writer.Write([]byte("Hello, Goal Framework!"))
})
// 启动服务
app.Call("start")
}
3. 路由配置
// GET路由
router.Get("/users", getUsers)
// POST路由
router.Post("/users", createUser)
// 路由分组
api := router.Group("/api/v1")
{
api.Get("/products", getProducts)
api.Post("/products", createProduct)
}
// 路径参数
router.Get("/users/{id}", getUserById)
4. 控制器使用
type UserController struct{}
func (ctrl *UserController) Index() interface{} {
return map[string]string{
"message": "用户列表",
}
}
func (ctrl *UserController) Show(id string) interface{} {
return map[string]string{
"id": id,
"message": "用户详情",
}
}
// 注册控制器路由
router.Resource("/users", &UserController{})
5. 中间件
// 自定义中间件
func AuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 认证逻辑
if r.Header.Get("Authorization") == "" {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
// 使用中间件
router.With(AuthMiddleware).Get("/profile", getProfile)
6. 数据库操作
Goal框架支持多种数据库驱动:
import "github.com/goal-web/database"
// 配置数据库
config := database.Config{
Default: "mysql",
Connections: map[string]interface{}{
"mysql": map[string]interface{}{
"driver": "mysql",
"host": "localhost",
"port": 3306,
"database": "test",
"username": "root",
"password": "password",
},
},
}
// 查询示例
var users []User
db.Table("users").Where("age > ?", 18).Get(&users)
7. 完整示例
package main
import (
"encoding/json"
"github.com/goal-web/application"
"github.com/goal-web/router"
"net/http"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
func main() {
app := application.NewApp()
router := app.Get("router").(*router.Router)
// 模拟数据
users := []User{
{ID: 1, Name: "Alice"},
{ID: 2, Name: "Bob"},
}
router.Get("/users", func(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(users)
})
router.Get("/users/{id}", func(w http.ResponseWriter, r *http.Request) {
// 获取路径参数
id := router.GetParam(r, "id")
for _, user := range users {
if fmt.Sprintf("%d", user.ID) == id {
json.NewEncoder(w).Encode(user)
return
}
}
http.NotFound(w, r)
})
app.Call("start")
}
优势特点
- 轻量高效:核心代码精简,性能优秀
- 易于扩展:支持中间件和插件机制
- RESTful支持:内置资源路由和REST API支持
- 依赖注入:内置IoC容器,管理组件依赖
通过以上示例,你可以快速开始使用Goal框架构建Go Web应用。建议查阅官方文档获取更详细的功能说明和最佳实践。