forked from mtusi2026/mtusi2026lab3
Исправить заголовок 413 и дополнить проверку отказов и масштабирования lab3
This commit is contained in:
@@ -0,0 +1,68 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/config"
|
||||
httpmodel "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/http"
|
||||
)
|
||||
|
||||
// TestBodyLimitInstanceHeader verifies parser-generated 413 responses over a real TCP listener.
|
||||
func TestBodyLimitInstanceHeader(t *testing.T) {
|
||||
// Arrange.
|
||||
ctrl := testController(t, func(cfg *config.Config) {
|
||||
cfg.HTTP.InstanceID = "body-limit-test-instance"
|
||||
})
|
||||
ctrl.cfg.Host = "127.0.0.1"
|
||||
ctrl.cfg.Port = 0
|
||||
address := make(chan string, 1)
|
||||
ctrl.server.Hooks().OnListen(func(data fiber.ListenData) error {
|
||||
address <- net.JoinHostPort(data.Host, data.Port)
|
||||
return nil
|
||||
})
|
||||
if err := ctrl.Start(t.Context()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
if err := ctrl.Stop(ctx); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
client := &http.Client{Timeout: 3 * time.Second}
|
||||
|
||||
// Act.
|
||||
response, err := client.Post("http://"+<-address+"/api/v1/users", "application/json", strings.NewReader(strings.Repeat("x", ctrl.cfg.MaxBodyBytes+1)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() {
|
||||
if err := response.Body.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}()
|
||||
|
||||
// Assert.
|
||||
if response.StatusCode != http.StatusRequestEntityTooLarge {
|
||||
t.Fatalf("status=%d", response.StatusCode)
|
||||
}
|
||||
if instance := response.Header.Get("X-Instance-Id"); instance != ctrl.instanceID {
|
||||
t.Fatalf("instance=%q, want %q", instance, ctrl.instanceID)
|
||||
}
|
||||
var body httpmodel.ErrorResponse
|
||||
if err := json.NewDecoder(response.Body).Decode(&body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if body.Error.Code != "payload_too_large" || body.Error.RequestID == "" || body.Error.RequestID != response.Header.Get(headerRequestID) {
|
||||
t.Fatalf("invalid error envelope: %+v", body)
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,8 @@ import (
|
||||
|
||||
// handleErr normalizes a failure and writes the public error envelope.
|
||||
func (ctrl *Controller) handleErr(ctx *fiber.Ctx, err error) error {
|
||||
// Parser failures such as BodyLimit rejection bypass request middleware.
|
||||
ctx.Set("X-Instance-Id", ctrl.instanceID)
|
||||
requestID := ctx.GetRespHeader(headerRequestID)
|
||||
if requestID == "" {
|
||||
requestID = uuid.NewString()
|
||||
|
||||
Reference in New Issue
Block a user