touka/docs/quickstart.md
wjqserver e4d3eed379 feat: redesign server startup around Run options
Replace the old RunShutdown and RunTLS style entry points with a single Run(opts...) API for v1. Add focused startup semantics tests, keep TLS and graceful shutdown independent, ensure sibling servers are cleaned up on startup failure, and update docs to match the new option-based startup model.
2026-04-07 17:44:55 +08:00

76 lines
1.8 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 快速开始
本指南将帮助您在几分钟内启动并运行一个 Touka 应用。
## 安装
确保您的环境中已经安装了 Go 1.26 或更高版本。
在您的项目目录中运行:
```bash
go get github.com/infinite-iroha/touka
```
## 基础示例
创建一个 `main.go` 文件,并粘贴以下代码:
```go
package main
import (
"net/http"
"time"
"log"
"github.com/infinite-iroha/touka"
)
func main() {
// 1. 创建默认引擎(包含 Recovery 中间件)
r := touka.Default()
// 2. 注册一个简单的 GET 路由
r.GET("/ping", func(c *touka.Context) {
c.JSON(http.StatusOK, touka.H{
"message": "pong",
"time": time.Now().Unix(),
})
})
// 3. 注册带参数的路由
r.GET("/hello/:name", func(c *touka.Context) {
name := c.Param("name")
c.String(http.StatusOK, "Hello, %s!", name)
})
// 4. 启动服务器并监听 8080 端口
log.Println("Touka server is running on :8080")
if err := r.Run(touka.WithAddr(":8080")); err != nil {
log.Fatalf("Server failed: %v", err)
}
}
```
## 运行应用
执行以下命令启动服务器:
```bash
go run main.go
```
现在,您可以访问:
- `http://localhost:8080/ping`
- `http://localhost:8080/hello/World`
## 优雅停机
在生产环境中,我们推荐为 `Run` 追加优雅关闭选项。启用后Touka 会监听 `SIGINT`/`SIGTERM`,在关闭时取消活动请求的上下文,并在超时前等待正在处理的请求完成。如需由应用内部事件触发关闭,还可以额外配合 `touka.WithShutdownContext(ctx)`
```go
// 等待 10 秒以处理剩余请求
if err := r.Run(touka.WithAddr(":8080"), touka.WithGracefulShutdown(10*time.Second)); err != nil {
log.Fatalf("Server forced to shutdown: %v", err)
}
```