- Google:授权码流程(openid email profile),handle 优先用已验证邮箱,头像取 picture - Telegram:官方 widget 直接回传签名资料,后端按官方算法验签(secret=SHA256(bot_token),除 hash 外全字段排序比对)+ auth_date 24h 时效 - providers 列表自动按配置下发(未配置的不显示);widget 型带 bot 用户名 - 三个登录方式共用读者会话与 upsert;Telegram 走 POST 无跳转 - .env.example 补 ONE_GOOGLE_* / ONE_TELEGRAM_* 模板
195 lines
6.1 KiB
Go
195 lines
6.1 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/auth"
|
|
"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"))
|
|
}
|
|
|
|
// 评论区的读者会话(cookie one_reader),30 天有效
|
|
readerSessions := auth.NewReaderSessions(cfg.SessionSec, 30*24*time.Hour)
|
|
// 后台管理员会话(cookie one_session),前台评论也用它识别站主身份
|
|
adminSessions := admin.NewSessions(cfg.SessionSec, 7*24*time.Hour)
|
|
|
|
public := &api.API{
|
|
Store: st,
|
|
Cfg: cfg,
|
|
Blobs: blobs,
|
|
ReaderSessions: readerSessions,
|
|
GH: auth.GitHub{ClientID: cfg.GitHubClientID, ClientSecret: cfg.GitHubClientSecret},
|
|
GG: auth.Google{ClientID: cfg.GoogleClientID, ClientSecret: cfg.GoogleClientSecret},
|
|
TG: auth.Telegram{Bot: cfg.TelegramBot, Token: cfg.TelegramToken},
|
|
AdminSessions: adminSessions,
|
|
}
|
|
adminAPI := admin.NewAPI(st, cfg, adminSessions)
|
|
adminAPI.Blobs = blobs
|
|
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>`
|
|
}
|