feat(http)!: 补齐核心请求处理与应用生命周期能力
Verify / verify (push) Canceled after 0s

增加安全字段校验提示、请求预算和就绪/存活探针,
让绑定、数据库、Redis 和出站响应解码保留可信诊断上下文。
补充完整应用装配及逆序清理示例,同步接入和迁移文档。

验证:make verify、make race-check 全部通过。

BREAKING CHANGE: 普通 Controller 默认启用 30 秒协作式请求预算,
可用 request_timeout_ms: 0 或 max-exec-time:"0" 关闭;
字段校验失败的 400 响应增加安全字段明细。
This commit is contained in:
zhangdeman committed 2026-11-26 20:41:33 -08:00
1 parent b4c3ac622c
commit 3196e45a01
22 files changed
+1294 -79

No files matched your search

+161
View File
@@ -0,0 +1,161 @@
package http
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"git.zhangdeman.cn/github/ginframework/database"
"git.zhangdeman.cn/github/ginframework/diagnostic"
"git.zhangdeman.cn/github/ginframework/httpclient"
"git.zhangdeman.cn/github/ginframework/internal/testutil/redisserver"
"git.zhangdeman.cn/github/ginframework/logger"
"git.zhangdeman.cn/github/ginframework/redis/commandlog"
"github.com/gin-gonic/gin"
redisclient "github.com/redis/go-redis/v9"
"go.uber.org/zap"
"go.uber.org/zap/zaptest/observer"
"gorm.io/driver/sqlite"
)
type flowTransport func(*http.Request) (*http.Response, error)
func (f flowTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
type flowForm struct {
Meta `path:"/context-flow" method:"GET"`
Bad bool `form:"bad"`
}
type flowController struct {
database *database.Connection
redis *redisclient.Client
outbound *httpclient.Client
}
func (c *flowController) Run(ctx *gin.Context, input *flowForm) (*exampleOutput, error) {
parent := ctx.Request.Context()
if err := c.database.Session(parent).Exec("SELECT 1").Error; err != nil {
return nil, err
}
if err := c.redis.Ping(parent).Err(); err != nil {
return nil, err
}
target := "https://example.test/ok"
if input.Bad {
target = "https://example.test/bad"
}
response, err := c.outbound.Send(parent, httpclient.Request{URL: target})
if err != nil {
return nil, err
}
var (
output exampleOutput
)
if err = response.DecodeJSON(&output); err != nil {
return nil, err
}
return &output, nil
}
func TestHTTPDatabaseRedisOutboundKeepOneDiagnosticSnapshot(t *testing.T) {
directory := t.TempDir()
if _, err := logger.ConfigureOutput(&logger.OutputConfig{Name: "default", Path: directory, UseJSON: true}); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = logger.CloseOutputs() })
sqlCore, sqlLogs := observer.New(zap.InfoLevel)
connection, err := database.Open(context.Background(), database.Config{Name: "test"}, database.Options{Dialector: sqlite.Open(":memory:"), Logger: zap.New(sqlCore)})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if err := connection.Close(); err != nil {
t.Error(err)
}
})
redis := redisserver.New(t, 3)
redisCore, redisLogs := observer.New(zap.InfoLevel)
redis.AddHook(commandlog.New(zap.New(redisCore), "test"))
outboundCore, outboundLogs := observer.New(zap.InfoLevel)
client, err := httpclient.New(httpclient.Config{}, httpclient.Options{Logger: zap.New(outboundCore), Transport: flowTransport(func(r *http.Request) (*http.Response, error) {
if diagnostic.From(r.Context()).TraceID == "" {
return nil, errors.New("outbound context lost")
}
if _, ok := r.Context().Deadline(); !ok {
return nil, errors.New("outbound budget lost")
}
body := `{"name":"ok"}`
if r.URL.Path == "/bad" {
body = `{"private-token":`
}
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body))}, nil
})})
if err != nil {
t.Fatal(err)
}
server, err := NewServer(Config{}, Options{})
if err != nil {
t.Fatal(err)
}
if err = server.Group("", nil, &flowController{database: connection, redis: redis, outbound: client}); err != nil {
t.Fatal(err)
}
var (
traces []string
)
for _, bad := range []bool{false, true} {
path := "/context-flow"
if bad {
path += "?bad=true"
}
recorder := httptest.NewRecorder()
server.Handler().ServeHTTP(recorder, httptest.NewRequest("GET", path, nil))
expected := 200
if bad {
expected = 500
}
if recorder.Code != expected {
t.Fatalf("flow status=%d: %s", recorder.Code, recorder.Body.String())
}
traces = append(traces, recorder.Header().Get("X-Request-ID"))
}
for _, trace := range traces {
if trace == "" {
t.Fatal("missing HTTP trace")
}
for name, logs := range map[string]*observer.ObservedLogs{"sql": sqlLogs, "redis": redisLogs, "outbound": outboundLogs} {
found := false
for _, entry := range logs.All() {
raw, _ := json.Marshal(entry.ContextMap())
if strings.Contains(string(raw), trace) {
found = true
break
}
}
if !found {
t.Fatalf("%s lost HTTP diagnostic snapshot %s", name, trace)
}
}
}
if err = logger.CloseOutputs(); err != nil {
t.Fatal(err)
}
paths, _ := filepath.Glob(filepath.Join(directory, "*"))
if len(paths) != 1 {
t.Fatal("source error log missing")
}
raw, err := os.ReadFile(paths[0])
if err != nil {
t.Fatal(err)
}
if strings.Count(strings.TrimSpace(string(raw)), "\n") != 0 || !strings.Contains(string(raw), traces[1]) || strings.Contains(string(raw), "private-token") {
t.Fatalf("outbound decode error lost context or logged twice: %s", raw)
}
}
Reference in new issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.