快速开始

快速开始

本章介绍如何在 5 分钟内把 go-web 跑起来。

环境要求

  • Go 1.25.0 或更高
  • 任意一种数据库(可选,首次试用可使用 memory 驱动跳过)
  • Redis(可选,缓存驱动可设为 none 跳过)

1. 克隆项目

git clone https://cnb.cool/mliev/open/go-web
cd go-web

2. 初始化项目(可选)

如果你 fork 后准备改造为自己的项目,执行初始化脚本一键替换模块路径:

./init.sh

脚本会把 cnb.cool/mliev/open/go-web 替换为你输入的新模块名,并执行 go mod tidy

3. 配置文件

cp config.yaml.example config.yaml
vim config.yaml

最小可运行配置(使用内存数据库 + 不启用缓存):

app:
  app_name: "my-app"
  mode: "debug"

database:
  driver: "memory"

cache:
  driver: "none"

config.yaml 中所有键都可以通过环境变量覆盖,规则是把 . 替换成 _,例如 database.driverDATABASE_DRIVER。详见「配置系统」章节。

4. 安装依赖并启动

go mod tidy
go run main.go start

启动后默认监听 :8080,直接访问健康检查接口:

curl http://127.0.0.1:8080/health/simple
# {"code":0,"message":"操作成功","data":{"status":"UP","timestamp":...}}

5. 进程管理子命令

go-web 通过 gomander 暴露了一组进程管理命令:

go run main.go start         # 前台启动
go run main.go start -d      # 守护进程模式
go run main.go stop          # 停止
go run main.go restart       # 重启
go run main.go reload        # 热重载(等价于 SIGHUP)
go run main.go status        # 查看状态

入口代码长什么样

main.go 仅 25 行,负责把模板/静态资源 embed 后交给 cmd.Start:

package main

import (
    "embed"

    "cnb.cool/mliev/open/go-web/cmd"
    "cnb.cool/mliev/open/go-web/config"
    "github.com/muleiwu/gomander"
)

//go:embed templates/**
var templateFS embed.FS

//go:embed static/**
var staticFs embed.FS

func main() {
    gomander.Run(func() {
        cmd.Start(
            cmd.WithTemplateFs(templateFS),
            cmd.WithWebStaticFs(staticFs),
            cmd.WithApp(config.App{}),
        )
    })
}

如果你想自定义装配链或 Server 列表,只需替换 config.App{} 为自己实现的 AppProvider。详见「启动流程与 AppProvider」章节。

常见问题

  • 启动卡在数据库连接 —— 检查 database.driver 是否与实际服务一致;首次试用建议先用 memory
  • Redis 缓存连不上 —— 把 cache.driver 设为 none 即可绕过 Redis
  • 端口被占用 —— go-web 默认监听 :8080,可通过 HTTP 服务的 listen 配置或自定义入口修改