feat(M1): Go API 服务器骨架 + Auth 中间件 + /health 端点

M1.3: Go HTTP 服务器 (net/http, /health, Auth middleware)
M1.4: Protobuf IPC 定义 (Go↔Rust Consolidation 服务)

验收:
- /health → 200 {"status":"ok","service":"zhiyid","version":"0.1.0"}
- 无 X-API-Key → 401
- 正确 Key → 200
- 错误 Key → 401

文件:
- go/cmd/zhiyid/main.go (127 行, 优雅关闭)
- go/internal/api/server.go (31 行, 路由注册)
- go/internal/api/middleware/auth.go (38 行, X-API-Key)
- go/internal/api/routes/health.go (24 行)
- go/proto/consolidate.proto (72 行, 4 RPC)
This commit is contained in:
xiaowei
2026-05-28 17:16:52 +08:00
parent cfb52518e4
commit 6667d42e14
6 changed files with 188 additions and 18 deletions
+33 -12
View File
@@ -1,13 +1,16 @@
// 织忆 MemoryWeave — Go API 服务 (zhiyid)
// port 7821
// 织忆 MemoryWeave — Go API 服务入口
package main
import (
"fmt"
"context"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/xiaoxue/memoryweave/internal/api"
)
func main() {
@@ -16,13 +19,31 @@ func main() {
port = "7821"
}
http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, `{"status":"ok","service":"zhiyid","version":"0.1.0-dev"}`)
})
log.Printf("zhiyid starting on :%s", port)
if err := http.ListenAndServe(":"+port, nil); err != nil {
log.Fatal(err)
srv := &http.Server{
Addr: "0.0.0.0:" + port,
Handler: api.NewServer(),
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 60 * time.Second,
}
// 优雅关闭
go func() {
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
<-sigCh
log.Println("[zhiyid] 收到关闭信号,正在退出...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Printf("[zhiyid] 关闭错误: %v", err)
}
}()
log.Printf("[zhiyid] 织忆 MemoryWeave 启动 — 端口 %s", port)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("[zhiyid] 启动失败: %v", err)
}
log.Println("[zhiyid] 已停止")
}
-6
View File
@@ -1,9 +1,3 @@
module github.com/xiaoxue/memoryweave
go 1.21
require (
github.com/go-redis/redis/v9 v9.0.0
github.com/gorilla/websocket v1.5.1
github.com/google/uuid v1.4.0
)
+41
View File
@@ -0,0 +1,41 @@
// API Key 认证中间件
package middleware
import (
"encoding/json"
"net/http"
"os"
)
// 豁免认证的路径
var exemptPaths = map[string]bool{
"/health": true,
}
// Auth 返回一个 HTTP 中间件,验证 X-API-Key 请求头
func Auth(next http.Handler) http.Handler {
apiKey := os.Getenv("API_KEY")
if apiKey == "" {
apiKey = "zhiyi-dev-key-2026"
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 豁免路径跳过认证
if exemptPaths[r.URL.Path] {
next.ServeHTTP(w, r)
return
}
key := r.Header.Get("X-API-Key")
if key != apiKey {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode(map[string]string{
"error": "unauthorized",
})
return
}
next.ServeHTTP(w, r)
})
}
+23
View File
@@ -0,0 +1,23 @@
// 健康检查端点
package routes
import (
"encoding/json"
"net/http"
)
// HandleHealth GET /health — 无需认证
func HandleHealth(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, `{"error":"method not allowed"}`, http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]string{
"status": "ok",
"service": "zhiyid",
"version": "0.1.0",
})
}
+26
View File
@@ -0,0 +1,26 @@
// HTTP 服务器 — 路由注册与启动
package api
import (
"log"
"net/http"
"github.com/xiaoxue/memoryweave/internal/api/middleware"
"github.com/xiaoxue/memoryweave/internal/api/routes"
)
// NewServer 创建已注册全部路由的 ServeMux
func NewServer() http.Handler {
mux := http.NewServeMux()
// 公共路由(无需认证)
mux.HandleFunc("/health", routes.HandleHealth)
// TODO: M3 阶段注册其他路由
// mux.HandleFunc("/api/v1/commit", ...)
// mux.HandleFunc("/api/v1/recall", ...)
// 全局 Auth 中间件
log.Println("[zhiyid] 路由注册完成")
return middleware.Auth(mux)
}
+65
View File
@@ -0,0 +1,65 @@
// Go ↔ Rust Consolidation Sidecar IPC 协议
// 通过 Unix Socket + Protobuf 通信
syntax = "proto3";
package consolidate;
option go_package = "github.com/xiaoxue/memoryweave/go/proto/consolidate";
// Consolidation 服务 — 由 Rust sidecar 实现,Go 调用
service Consolidation {
// 运行完整深度整合流程
rpc RunFull(RunFullRequest) returns (RunFullResponse);
// DBSCAN 跨记忆聚类
rpc RunClustering(RunClusteringRequest) returns (RunClusteringResponse);
// 衰减模型回归拟合
rpc RunRegression(RunRegressionRequest) returns (RunRegressionResponse);
// 蒸馏质量反向测试
rpc RunQualityCheck(RunQualityCheckRequest) returns (RunQualityCheckResponse);
}
message RunFullRequest {
string data_dir = 1; // LanceDB 数据目录
}
message RunFullResponse {
bool success = 1;
int32 cluster_count = 2;
double decay_rate_updated = 3;
double quality_score = 4;
string error_message = 5;
}
message RunClusteringRequest {
string data_dir = 1;
double eps = 2; // DBSCAN 邻域半径
int32 min_samples = 3;
}
message RunClusteringResponse {
int32 cluster_count = 1;
repeated string labels = 2;
}
message RunRegressionRequest {
string data_dir = 1;
}
message RunRegressionResponse {
double decay_rate = 1;
double r_squared = 2;
}
message RunQualityCheckRequest {
string data_dir = 1;
int32 sample_size = 2; // 抽样大小,默认 20
}
message RunQualityCheckResponse {
double avg_cosine_similarity = 1;
bool pass_threshold = 2;
int32 sample_count = 3;
}