Altar 的后端 API 服务,基于 Go、Gin 和 PostgreSQL。当前服务用于写入留言,并随机读取最多 20 条留言。
- Go 1.25.5
- Gin
- PostgreSQL
- godotenv
- 已安装 Go
- 已安装并启动 PostgreSQL
- 已创建目标数据库
服务启动时会读取项目根目录下的 .env 文件,也可以直接使用系统环境变量。
DB_HOST=localhost
DB_PORT=5432
DB_USER=postgres
DB_PASS=postgres
DB_NAME=altar当前代码依赖 messages 表。可以用下面的 SQL 初始化:
CREATE TABLE IF NOT EXISTS messages (
id SERIAL PRIMARY KEY,
content TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);go mod downloadgo run .服务默认监听:
http://localhost:8005
编译后的服务名称为 altar-api:
go build -o altar-api .仓库中提供了 altar-api.service,默认运行用户为 admin,部署目录为 /home/admin/altar/server。如果实际部署目录不同,需要同步修改服务文件里的 WorkingDirectory、EnvironmentFile 和 ExecStart。
安装并启用服务:
sudo cp altar-api.service /etc/systemd/system/altar-api.service
sudo systemctl daemon-reload
sudo systemctl enable --now altar-api查看服务状态和日志:
sudo systemctl status altar-api
sudo journalctl -u altar-api -fPOST /messages
Content-Type: application/json请求体:
{
"content": "hello altar"
}成功响应:
201 Created
GET /messages成功响应:
[
"hello altar",
"another message"
]接口会从数据库中随机返回最多 20 条留言。
写入一条留言:
curl -X POST http://localhost:8005/messages \
-H "Content-Type: application/json" \
-d '{"content":"hello altar"}'读取留言:
curl http://localhost:8005/messages