存储抽象(internal/storage,新包)
- BlobStore 接口(Put / Open / Delete)+ 两个实现:R2(aws-sdk-go-v2 走
R2 的 S3 兼容 API,path-style、region auto)与本地磁盘(DataDir/uploads,
零配置兜底)。选择:Endpoint / S3Api / Bucket / AccessKey / SecretAccessKey
齐全 → R2,缺任一项回落本地并在启动日志提示缺失的字段名(只报名字不报值)
- 端点 URL 里的路径段不交给 SDK:path-style 下它会被折进对象 key,
导致「数据库 key」和「实际对象 key」对不上(直链 404,实测复现)。
EndpointKeyPrefix 提取路径段给上传 handler 拼进 key,StripEndpointPath
只取 scheme://host 给 SDK——数据库 / 存储端 / 直链三方一致
数据与 API
- files 表:id / key(唯一) / name / mime / size / sha256 / store(r2|local) /
created_at;URL 不入库,按「store 来源 + PublicBase」响应时解析,
切存储端不破坏存量链接
- POST /api/admin/files:multipart 多文件,单文件 ≤50MB(MaxBytesReader 64MB);
类型白名单 = 图片(jpg/png/webp/gif/avif)+ 附件(pdf/zip/txt),
扩展名 + http.DetectContentType 双重校验(实测拦截随机字节改名 .png),
SVG 拒绝(同源脚本);内容 sha256 做 key(2026/09/{哈希前12位}{扩展名}),
同内容重复上传自动去重复用
- GET /api/admin/files(分页 + 文件名搜索)、DELETE /{id}(先删对象再删行,
存储端失败保留行可重试)
- 公开路由 GET /uploads/{key}(main.go 挂载):按 key 查行、存储层流式返回,
Cache-Control immutable + ETag 304;R2 + PublicBase 时 302 直链(后端不出流量)
- URL 解析:FileURL(store, key, PublicBase)——R2 且配了公开域名走直链,
否则 /uploads/ 流式
后台文件管理页(FilesView,「工作台 → 文件」)
- 点击 / 拖拽多选上传(uploadFiles 走 FormData 裸 fetch,401 广播与
request() 一致);缩略图卡片网格(图片出图、其他出类型占位);
复制链接(clipboard,非 https 回落 prompt)/ 打开 / 删除(确认提示);
分页、loading/empty 沿用既有模式
编辑器联动(EditorView)
- 封面:URL 输入框旁「上传」按钮,选图自动填 cover_url
- wysiwyg:Crepe ImageBlock 官方 onUpload 钩子——粘贴 / 拖拽 / 插图
全部走上传,返回 URL 后由 Crepe 插节点
- Markdown 模式:插图弹层加「上传」按钮 + 编辑器粘贴 / 拖拽图片,
上传后在原光标处插入 (异步上传先记光标位,逐张追踪偏移)
.env.example
- 模板入库(无敏感值):Endpoint = 公开访问域名(直链)、S3Api = 上传端点、
Bucket / AccessKey / SecretAccessKey
验证
- 本地兜底全流程:上传 201、同内容去重复用、随机字节改名 .png 被
内容嗅探拒绝、.svg 拒绝、公开路由 immutable 缓存头 + 内容一致、
删除后存储与公开路由双清 404
- R2 真实链路(站主 .env):上传 store=r2、直链 200(过程中定位并修复
S3Api 路径段折进 key 导致的直链 404,见 EndpointKeyPrefix)
- 后端 go build/test/vet 全绿;前端构建通过
179 lines
5.4 KiB
Go
179 lines
5.4 KiB
Go
// Command one-server is the ONE blog backend: public API, admin API, RSS and
|
|
// (when built) the static frontend.
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"flag"
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"path/filepath"
|
|
"strings"
|
|
"syscall"
|
|
"time"
|
|
|
|
"oneblog/internal/admin"
|
|
"oneblog/internal/api"
|
|
"oneblog/internal/config"
|
|
"oneblog/internal/db"
|
|
"oneblog/internal/storage"
|
|
"oneblog/internal/store"
|
|
)
|
|
|
|
func main() {
|
|
addr := flag.String("addr", "", "listen address (overrides ONE_ADDR)")
|
|
flag.Parse()
|
|
|
|
cfg, err := config.Load()
|
|
if err != nil {
|
|
log.Fatalf("config: %v", err)
|
|
}
|
|
if *addr != "" {
|
|
cfg.Addr = *addr
|
|
}
|
|
|
|
pool, err := db.Open(cfg.Driver, cfg.DSN)
|
|
if err != nil {
|
|
log.Fatalf("database: %v", err)
|
|
}
|
|
defer pool.Close()
|
|
|
|
st, err := store.New(pool)
|
|
if err != nil {
|
|
log.Fatalf("store: %v", err)
|
|
}
|
|
|
|
// 文件上传的存储后端:R2 配置齐全用 R2,否则本地磁盘兜底。
|
|
// 两个 API 共享同一实例;公开访问路由 /uploads/ 也走它。
|
|
var blobs storage.BlobStore
|
|
switch cfg.StorageDriver {
|
|
case "r2":
|
|
blobs, err = storage.NewR2(cfg.S3Endpoint, cfg.R2Bucket, cfg.R2AccessKey, cfg.R2SecretKey)
|
|
if err != nil {
|
|
log.Fatalf("storage: %v", err)
|
|
}
|
|
default:
|
|
blobs = storage.NewLocal(filepath.Join(cfg.DataDir, "uploads"))
|
|
}
|
|
|
|
public := &api.API{Store: st, Cfg: cfg, Blobs: blobs}
|
|
adminAPI := admin.NewAPI(st, cfg, admin.NewSessions(cfg.SessionSec, 7*24*time.Hour))
|
|
adminAPI.Blobs = blobs
|
|
|
|
root := http.NewServeMux()
|
|
root.Handle("/api/admin/", adminAPI.Routes())
|
|
public.Mount(root)
|
|
root.Handle("/uploads/", public.UploadsHandler())
|
|
root.Handle("/", spaHandler(cfg.WebDist))
|
|
|
|
srv := &http.Server{
|
|
Addr: cfg.Addr,
|
|
Handler: requestLog(root),
|
|
ReadTimeout: 15 * time.Second,
|
|
WriteTimeout: 60 * time.Second,
|
|
IdleTimeout: 60 * time.Second,
|
|
}
|
|
|
|
go func() {
|
|
log.Printf("ONE server listening on %s (db=%s)", cfg.Addr, cfg.Driver)
|
|
if cfg.InsecureDev {
|
|
log.Printf("admin login: %s / %s (set ONE_ADMIN_PASSWORD to change)", cfg.AdminUser, cfg.AdminPass)
|
|
} else {
|
|
log.Printf("admin login: %s / (from ONE_ADMIN_PASSWORD)", cfg.AdminUser)
|
|
}
|
|
if !dirExists(cfg.WebDist) {
|
|
log.Printf("frontend build not found at %s · run `make web` or `make dev` (API still available)", cfg.WebDist)
|
|
}
|
|
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
|
log.Fatalf("listen: %v", err)
|
|
}
|
|
}()
|
|
|
|
stop := make(chan os.Signal, 1)
|
|
signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
|
|
<-stop
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
_ = srv.Shutdown(ctx)
|
|
log.Print("bye")
|
|
}
|
|
|
|
// spaHandler serves the built Vue app and falls back to index.html so client
|
|
// routes like /post/foo work on refresh.
|
|
func spaHandler(dist string) http.Handler {
|
|
fs := http.Dir(dist)
|
|
fileServer := http.FileServer(fs)
|
|
index := filepath.Join(dist, "index.html")
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if !dirExists(dist) {
|
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
|
fmt.Fprint(w, placeholderPage())
|
|
return
|
|
}
|
|
p := strings.TrimPrefix(r.URL.Path, "/")
|
|
if p == "" {
|
|
p = "index.html"
|
|
}
|
|
if _, err := fs.Open(p); err == nil && hasExt(p) {
|
|
// 缓存策略分两类:
|
|
// assets/ 下的文件名带内容 hash(Vite 产物),内容变了文件名就变,
|
|
// 所以可以长期强缓存;其余(主要是 index.html)必须每次回源校验,
|
|
// 否则新构建不会生效 : 页面「改了但看着还是旧的」通常就是它。
|
|
if strings.HasPrefix(p, "assets/") {
|
|
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
|
|
} else {
|
|
w.Header().Set("Cache-Control", "no-cache, must-revalidate")
|
|
}
|
|
fileServer.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
w.Header().Set("Cache-Control", "no-cache, must-revalidate")
|
|
http.ServeFile(w, r, index)
|
|
})
|
|
}
|
|
|
|
func hasExt(p string) bool {
|
|
return strings.Contains(filepath.Base(p), ".")
|
|
}
|
|
|
|
func dirExists(p string) bool {
|
|
fi, err := os.Stat(p)
|
|
return err == nil && fi.IsDir()
|
|
}
|
|
|
|
func requestLog(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
start := time.Now()
|
|
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
|
|
next.ServeHTTP(rec, r)
|
|
if strings.HasPrefix(r.URL.Path, "/api") || r.URL.Path == "/rss.xml" {
|
|
log.Printf("%s %s %d %s", r.Method, r.URL.RequestURI(), rec.status, time.Since(start).Truncate(time.Millisecond))
|
|
}
|
|
})
|
|
}
|
|
|
|
type statusRecorder struct {
|
|
http.ResponseWriter
|
|
status int
|
|
}
|
|
|
|
func (s *statusRecorder) WriteHeader(code int) { s.status = code; s.ResponseWriter.WriteHeader(code) }
|
|
|
|
func placeholderPage() string {
|
|
return `<!doctype html><meta charset="utf-8"><title>ONE</title>
|
|
<style>body{font-family:-apple-system,"PingFang SC",sans-serif;background:#faf7f1;color:#33302b;
|
|
display:flex;align-items:center;justify-content:center;height:100vh;margin:0}
|
|
div{max-width:520px;line-height:1.95;padding:0 24px}
|
|
code{background:#efe9dd;padding:2px 6px;border-radius:3px}</style>
|
|
<div><h1 style="font-family:Georgia,serif">ONE · 一个博客</h1>
|
|
<p>后端已启动,但前端还没构建。</p>
|
|
<p>在项目根目录执行 <code>make web</code> 构建前端,或 <code>make dev</code> 同时起前后端。</p>
|
|
<p>接口可用:<code>/api/posts</code>、<code>/api/archive</code>、<code>/api/tags</code>、<code>/rss.xml</code>;后台接口在 <code>/api/admin/</code>。</p></div>`
|
|
}
|