feat: add HTTP migration bridges and extensible API binding
This commit is contained in:
@@ -75,8 +75,8 @@ Handler / Service / Repository / Model 与模块注册入口。模块名为 lowe
|
||||
从远程安装,生成一个带 Handler / Service / Repository / Model 分层的服务骨架:
|
||||
|
||||
```sh
|
||||
GOPRIVATE=git.yuntuo.hk go install git.yuntuo.hk/k2safe/go-omni/cmd/go-omni@v0.8.0-preview
|
||||
go-omni new --framework-version v0.8.0-preview --module example.com/billing ./billing
|
||||
GOPRIVATE=git.yuntuo.hk go install git.yuntuo.hk/k2safe/go-omni/cmd/go-omni@v0.9.0-preview
|
||||
go-omni new --framework-version v0.9.0-preview --module example.com/billing ./billing
|
||||
cd billing
|
||||
go mod tidy
|
||||
go run ./cmd/server
|
||||
|
||||
161
cmd/go-omni/apigen/compatibility_test.go
Normal file
161
cmd/go-omni/apigen/compatibility_test.go
Normal file
@@ -0,0 +1,161 @@
|
||||
package apigen
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestCompatibilityContract(t *testing.T) {
|
||||
s, err := Parse(filepath.Join(frameworkRoot(t), "examples/contracts/compatibility.api"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c, err := Compile(s)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(s.Scalars) != 1 || len(s.Routes) != 6 {
|
||||
t.Fatal("incomplete contract")
|
||||
}
|
||||
if !strings.Contains(string(c.Document), `"anyOf"`) || !strings.Contains(string(c.Document), `"multipart/form-data"`) {
|
||||
t.Fatal("missing schemas")
|
||||
}
|
||||
for _, change := range [][2]string{{"jsonInput: string | int64", "jsonInput: mystery"}, {"text: true", "text: false"}, {"mode: multipart", "mode: invalid"}, {"maxBytes: 128", "maxBytes: 0"}, {"goType: ID", "goType: id"}, {"Data any", "Data interface{ Method() }"}} {
|
||||
source := readFile(t, filepath.Join(frameworkRoot(t), "examples/contracts/compatibility.api"))
|
||||
spec, err := parseText(t, strings.Replace(source, change[0], change[1], 1))
|
||||
if err == nil {
|
||||
_, err = Compile(spec)
|
||||
}
|
||||
if err == nil {
|
||||
t.Fatalf("accepted %s", change[1])
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestCompatibilityConsumer(t *testing.T) {
|
||||
if os.Getenv("GO_OMNI_SCAFFOLD_INTEGRATION") == "" {
|
||||
t.Skip("consumer integration")
|
||||
}
|
||||
root := frameworkRoot(t)
|
||||
dir := filepath.Join(t.TempDir(), "consumer")
|
||||
o := Options{API: filepath.Join(root, "examples/contracts/compatibility.api"), Dir: dir, Module: "example.com/compatibility", FrameworkDir: root}
|
||||
releaseCLI := os.Getenv("GO_OMNI_RELEASE_CLI")
|
||||
generate := func(check bool) {
|
||||
t.Helper()
|
||||
if releaseCLI == "" {
|
||||
options := o
|
||||
options.Check = check
|
||||
if _, err := Generate(options); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
args := []string{"api", "generate", "--api", o.API, "--dir", dir, "--module", o.Module}
|
||||
if check {
|
||||
args = append(args, "--check")
|
||||
}
|
||||
cmd := exec.CommandContext(ctx, releaseCLI, args...)
|
||||
cmd.Dir = filepath.Dir(dir)
|
||||
if output, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("released CLI: %v\n%s", err, output)
|
||||
}
|
||||
}
|
||||
generate(false)
|
||||
files := map[string]string{
|
||||
"internal/service/demo/echo.go": "echo.go",
|
||||
"internal/handler/demo/customBind.go": "hooks.go",
|
||||
"internal/handler/files/downloadManual.go": "download.go",
|
||||
"consumer_test.go": "consumer_test.go",
|
||||
}
|
||||
// The fixture implements related methods together; remove only its generated
|
||||
// one-time stubs, then fill every stub so regeneration can preserve all files.
|
||||
for _, name := range []string{"internal/service/demo/item.go", "internal/service/demo/custom.go"} {
|
||||
writeFile(t, filepath.Join(dir, name), "package demo\n")
|
||||
}
|
||||
for _, name := range []string{"internal/handler/demo/uploadManual.go", "internal/handler/demo/callbackManual.go"} {
|
||||
writeFile(t, filepath.Join(dir, name), "package demo\n")
|
||||
}
|
||||
for target, source := range files {
|
||||
writeFile(t, filepath.Join(dir, target), readFile(t, filepath.Join("testdata/compatibility", source)))
|
||||
}
|
||||
before := map[string]string{}
|
||||
for target := range files {
|
||||
before[target] = readFile(t, filepath.Join(dir, target))
|
||||
}
|
||||
generate(false)
|
||||
for target, content := range before {
|
||||
if readFile(t, filepath.Join(dir, target)) != content {
|
||||
t.Fatalf("overwrote %s", target)
|
||||
}
|
||||
}
|
||||
generate(true)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, "go", "test", "-mod=mod", "-race", "-count=1", "./...")
|
||||
cmd.Dir = dir
|
||||
cmd.Env = append(os.Environ(), "GOWORK=off")
|
||||
if output, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("consumer: %v\n%s", err, output)
|
||||
}
|
||||
if releaseCLI != "" {
|
||||
cmd = exec.CommandContext(ctx, "go", "list", "-m", "-json", frameworkModule)
|
||||
cmd.Dir = dir
|
||||
cmd.Env = append(os.Environ(), "GOWORK=off")
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("module: %v\n%s", err, output)
|
||||
}
|
||||
var module struct {
|
||||
Version, Sum string
|
||||
Replace any
|
||||
}
|
||||
if err = json.Unmarshal(output, &module); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if module.Version != os.Getenv("GO_OMNI_RELEASE_VERSION") || module.Replace != nil || module.Sum == "" {
|
||||
t.Fatalf("not a fixed remote dependency: %+v", module)
|
||||
}
|
||||
t.Logf("remote framework %s checksum %s; no local replace", module.Version, module.Sum)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestNestedDynamicAliases(t *testing.T) {
|
||||
source := readFile(t, filepath.Join(frameworkRoot(t), "examples/contracts/compatibility.api"))
|
||||
for _, typ := range []string{"[]interface{}", "map[string]interface{}", "map[string][]interface{}"} {
|
||||
s, err := parseText(t, strings.Replace(source, "Data any", "Data "+typ, 1))
|
||||
if err == nil {
|
||||
_, err = Compile(s)
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", typ, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestSwitchFromManualRequiresExplicitMigration(t *testing.T) {
|
||||
root := frameworkRoot(t)
|
||||
o := Options{API: filepath.Join(root, "examples/contracts/compatibility.api"), Dir: filepath.Join(t.TempDir(), "consumer"), Module: "example.com/compatibility", FrameworkDir: root}
|
||||
if _, err := Generate(o); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The hand-written source may contain business code. Never delete it to make
|
||||
// the newly automatic handler compile; fail before touching generated files.
|
||||
o.API = filepath.Join(o.Dir, "api/compatibility.api")
|
||||
source := readFile(t, o.API)
|
||||
source = strings.Replace(source, "@handlerMode manual\n @produces \"application/octet-stream\"", "", 1)
|
||||
writeFile(t, o.API, source)
|
||||
before := snapshot(t, o.Dir)
|
||||
if _, err := Generate(o); err == nil || !strings.Contains(err.Error(), "migrate and remove") {
|
||||
t.Fatalf("unsafe mode switch: %v", err)
|
||||
}
|
||||
if !sameFiles(before, snapshot(t, o.Dir)) {
|
||||
t.Fatal("failed mode switch mutated project")
|
||||
}
|
||||
}
|
||||
@@ -42,6 +42,9 @@ func Compile(spec *Spec) (*Compiled, error) {
|
||||
}
|
||||
definitions := map[string]Type{}
|
||||
for _, t := range spec.Types {
|
||||
if t.Name == "ContractScalars" && len(spec.Scalars) > 0 {
|
||||
return nil, errors.New("ContractScalars is reserved when declaring scalars")
|
||||
}
|
||||
if !exportedName.MatchString(t.Name) {
|
||||
return nil, fmt.Errorf("%s: type names must be UpperCamelCase", t.Position)
|
||||
}
|
||||
@@ -50,17 +53,24 @@ func Compile(spec *Spec) (*Compiled, error) {
|
||||
}
|
||||
definitions[t.Name] = t
|
||||
}
|
||||
scalarTypes, scalarDefs, err := compileScalars(spec, definitions)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resolved := map[string]reflect.Type{}
|
||||
resolving := map[string]bool{}
|
||||
var resolve func(string, int) (reflect.Type, error)
|
||||
var expression func(ast.Expr, int) (reflect.Type, error)
|
||||
primitives := map[string]reflect.Type{"string": reflect.TypeOf(""), "bool": reflect.TypeOf(false), "int": reflect.TypeOf(int(0)), "int8": reflect.TypeOf(int8(0)), "int16": reflect.TypeOf(int16(0)), "int32": reflect.TypeOf(int32(0)), "int64": reflect.TypeOf(int64(0)), "uint": reflect.TypeOf(uint(0)), "uint8": reflect.TypeOf(uint8(0)), "uint16": reflect.TypeOf(uint16(0)), "uint32": reflect.TypeOf(uint32(0)), "uint64": reflect.TypeOf(uint64(0)), "float32": reflect.TypeOf(float32(0)), "float64": reflect.TypeOf(float64(0))}
|
||||
primitives := map[string]reflect.Type{"any": reflect.TypeOf((*any)(nil)).Elem(), "string": reflect.TypeOf(""), "bool": reflect.TypeOf(false), "int": reflect.TypeOf(int(0)), "int8": reflect.TypeOf(int8(0)), "int16": reflect.TypeOf(int16(0)), "int32": reflect.TypeOf(int32(0)), "int64": reflect.TypeOf(int64(0)), "uint": reflect.TypeOf(uint(0)), "uint8": reflect.TypeOf(uint8(0)), "uint16": reflect.TypeOf(uint16(0)), "uint32": reflect.TypeOf(uint32(0)), "uint64": reflect.TypeOf(uint64(0)), "float32": reflect.TypeOf(float32(0)), "float64": reflect.TypeOf(float64(0))}
|
||||
expression = func(e ast.Expr, depth int) (reflect.Type, error) {
|
||||
if depth > 32 {
|
||||
return nil, errors.New("type nesting exceeds 32")
|
||||
}
|
||||
switch e := e.(type) {
|
||||
case *ast.Ident:
|
||||
if t, ok := scalarTypes[e.Name]; ok {
|
||||
return t, nil
|
||||
}
|
||||
if t, ok := primitives[e.Name]; ok {
|
||||
return t, nil
|
||||
}
|
||||
@@ -140,7 +150,7 @@ func Compile(spec *Spec) (*Compiled, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b, err := contract.ForType(rt)
|
||||
b, err := contract.Describe(rt, scalarDefs...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", t.Position, err)
|
||||
}
|
||||
@@ -217,12 +227,15 @@ func Compile(spec *Spec) (*Compiled, error) {
|
||||
if r.Status != 200 && r.Status != 201 && r.Status != 202 && r.Status != 204 {
|
||||
return nil, errors.New("@status supports 200, 201, 202 or 204")
|
||||
}
|
||||
if (r.Status == 204) != (r.Response == "") {
|
||||
if !r.Manual && (r.Status == 204) != (r.Response == "") {
|
||||
return nil, errors.New("204 requires no response; other success statuses require a response type")
|
||||
}
|
||||
if r.Method == "head" && r.Response != "" {
|
||||
return nil, errors.New("HEAD must not declare a response body")
|
||||
}
|
||||
if err := validateRouteExtensions(r); err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", r.Position, err)
|
||||
}
|
||||
op := openapi.Operation{Method: r.Method, Path: r.Path, OperationID: operationID(r), Summary: r.Summary, Responses: map[int]openapi.Response{}}
|
||||
if r.Request != "" {
|
||||
b, ok := c.Bindings[r.Request]
|
||||
@@ -231,6 +244,9 @@ func Compile(spec *Spec) (*Compiled, error) {
|
||||
}
|
||||
op.Parameters = b.Parameters()
|
||||
op.Request = b.BodySchema()
|
||||
if op.Request != nil && (r.BodyMode == "raw" || r.BodyMode == "multipart") {
|
||||
return nil, errors.New("raw/multipart request DTOs may declare only path/form/header fields; body binding is manual")
|
||||
}
|
||||
if op.Request != nil && (r.Method == "get" || r.Method == "head") {
|
||||
return nil, errors.New("GET/HEAD requests cannot declare JSON bodies; use form/path/header tags")
|
||||
}
|
||||
|
||||
@@ -140,6 +140,7 @@ func decorateDocument(doc map[string]any, spec *Spec) {
|
||||
}
|
||||
}
|
||||
op := doc["paths"].(map[string]any)[strings.Join(parts, "/")].(map[string]any)[r.Method].(map[string]any)
|
||||
decorateRequestOptions(op, r)
|
||||
if r.ResponseFormat != "" {
|
||||
op["x-omni-response"] = r.ResponseFormat
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ import (
|
||||
)
|
||||
|
||||
const frameworkModule = "git.yuntuo.hk/k2safe/go-omni"
|
||||
const minimumVersion = "v0.8.0-preview"
|
||||
const minimumVersion = "v0.9.0-preview"
|
||||
const generatedHeader = "// Code generated by go-omni api. DO NOT EDIT.\n"
|
||||
|
||||
type Options struct {
|
||||
@@ -94,6 +94,16 @@ func generate(o Options, c *Compiled, starter bool) (Output, error) {
|
||||
return Output{}, err
|
||||
}
|
||||
o.Dir = directory
|
||||
for _, r := range c.Spec.Routes {
|
||||
if !r.Manual {
|
||||
path := filepath.Join(directory, "internal/handler", r.Group, lower(r.Handler)+"Manual.go")
|
||||
if _, err := os.Lstat(path); err == nil {
|
||||
return Output{}, fmt.Errorf("manual handler %s exists; migrate and remove it explicitly before switching to automatic generation", path)
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return Output{}, err
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := resolveProfile(&o); err != nil {
|
||||
return Output{}, err
|
||||
}
|
||||
@@ -130,13 +140,13 @@ func generate(o Options, c *Compiled, starter bool) (Output, error) {
|
||||
if !filepath.IsAbs(path) {
|
||||
path = filepath.Join(directory, path)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(path, "httpx", "response.go")); err == nil {
|
||||
if _, err := os.Stat(filepath.Join(path, "contract", "scalar.go")); err == nil {
|
||||
localCurrent = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if !localCurrent {
|
||||
return Output{}, fmt.Errorf("existing framework dependency predates configurable responses; use %s or a current local replacement", minimumVersion)
|
||||
return Output{}, fmt.Errorf("existing framework dependency predates migration extensions; use %s or a current local replacement", minimumVersion)
|
||||
}
|
||||
}
|
||||
if o.FrameworkDir != "" {
|
||||
@@ -309,6 +319,20 @@ func renderProject(o Options, c *Compiled, starter bool) (map[string][]byte, map
|
||||
put(generated, "internal/apierrors/errorsGen.go", generatedHeader+content)
|
||||
}
|
||||
types := "package types\n\n"
|
||||
if len(c.Spec.Scalars) > 0 {
|
||||
types += "import("
|
||||
for i, d := range c.Spec.Scalars {
|
||||
types += fmt.Sprintf("scalar%d %q;", i, d.GoImport)
|
||||
}
|
||||
types += ")\n"
|
||||
registry := fmt.Sprintf("package types\nimport %q\nfunc ContractScalars()[]contract.Scalar{return []contract.Scalar{", frameworkModule+"/contract")
|
||||
for i, d := range c.Spec.Scalars {
|
||||
types += fmt.Sprintf("type %s = scalar%d.%s\n", d.Name, i, d.GoType)
|
||||
registry += fmt.Sprintf("contract.ScalarOf[%s](%q,%q,%t),", d.Name, d.JSONInput, d.JSONOutput, d.Text)
|
||||
}
|
||||
registry += "}}\n"
|
||||
put(generated, "internal/types/scalarsGen.go", generatedHeader+registry)
|
||||
}
|
||||
for _, t := range c.Spec.Types {
|
||||
types += "type " + t.Name + " struct {\n"
|
||||
for _, f := range t.Fields {
|
||||
@@ -331,6 +355,10 @@ func renderProject(o Options, c *Compiled, starter bool) (map[string][]byte, map
|
||||
put(generated, "internal/handler/responseGen.go", generatedHeader+policySource)
|
||||
imports := fmt.Sprintf("import (\"fmt\"; %q; %q; %q;", frameworkModule+"/httpx", frameworkModule+"/openapi", o.Module+"/internal/servicecontext")
|
||||
routes := "func RegisterRoutes(router openapi.Registrar, deps *servicecontext.Context) error {\n if router==nil || deps==nil {return fmt.Errorf(\"router and dependencies required\")}\n"
|
||||
if len(c.Spec.Scalars) > 0 {
|
||||
imports += fmt.Sprintf("%q;%q;", frameworkModule+"/contract", o.Module+"/internal/types")
|
||||
routes += "if err:=contract.ValidateScalars(types.ContractScalars()...);err!=nil{return err}\n"
|
||||
}
|
||||
middlewareSet := map[string]bool{}
|
||||
for _, r := range c.Spec.Routes {
|
||||
for _, m := range r.Middleware {
|
||||
@@ -347,7 +375,7 @@ func renderProject(o Options, c *Compiled, starter bool) (map[string][]byte, map
|
||||
}
|
||||
for i, group := range c.Groups {
|
||||
imports += fmt.Sprintf("h%d %q; s%d %q;", i, o.Module+"/internal/handler/"+group, i, o.Module+"/internal/service/"+group)
|
||||
routes += fmt.Sprintf("h%d := h%d.New(s%d.New(deps))\n", i, i, i)
|
||||
routes += fmt.Sprintf("h%d := h%d.New(s%d.New(deps),deps)\n", i, i, i)
|
||||
groupRoutes := []Route{}
|
||||
for _, r := range c.Spec.Routes {
|
||||
if r.Group == group {
|
||||
@@ -356,12 +384,16 @@ func renderProject(o Options, c *Compiled, starter bool) (map[string][]byte, map
|
||||
}
|
||||
packageName := filepath.Base(group)
|
||||
text := "package " + packageName + "\nimport(\"context\"; \"fmt\";"
|
||||
needsTypes, needsBinder := false, false
|
||||
needsTypes, needsBinder, hasAutomatic := false, false, false
|
||||
for _, r := range groupRoutes {
|
||||
if r.Manual {
|
||||
continue
|
||||
}
|
||||
hasAutomatic = true
|
||||
needsTypes = needsTypes || r.Request != "" || r.Response != ""
|
||||
needsBinder = needsBinder || r.Request != ""
|
||||
needsBinder = needsBinder || (r.Request != "" && !r.CustomBinding)
|
||||
}
|
||||
text += fmt.Sprintf("%q;", frameworkModule+"/httpx")
|
||||
text += fmt.Sprintf("%q;%q;", frameworkModule+"/httpx", o.Module+"/internal/servicecontext")
|
||||
if needsTypes {
|
||||
text += fmt.Sprintf("%q;", o.Module+"/internal/types")
|
||||
}
|
||||
@@ -371,18 +403,47 @@ func renderProject(o Options, c *Compiled, starter bool) (map[string][]byte, map
|
||||
text += ")\n"
|
||||
text += "type Service interface {\n"
|
||||
for _, r := range groupRoutes {
|
||||
text += signature(r) + "\n"
|
||||
if !r.Manual {
|
||||
text += signature(r) + "\n"
|
||||
}
|
||||
}
|
||||
text += "}\ntype Handler struct {service Service}\nfunc New(s Service)*Handler {return &Handler{service:s}}\n"
|
||||
text += "}\ntype Handler struct {service Service;deps *servicecontext.Context}\nfunc New(s Service,deps ...*servicecontext.Context)*Handler {h:=&Handler{service:s};if len(deps)>0{h.deps=deps[0]};return h}\n"
|
||||
for _, r := range groupRoutes {
|
||||
name := upper(r.Handler)
|
||||
if r.Request != "" {
|
||||
text += fmt.Sprintf("var %sRequest = contract.MustNew[types.%s]()\n", lower(r.Handler), r.Request)
|
||||
// The response policy and body reader cap are installed before App middleware.
|
||||
if r.MaxBodyBytes > 0 {
|
||||
routes += fmt.Sprintf("httpx.HandleWithBodyLimit(router,%q,%q,%d,responseEncoder(%q,%t),h%d.%s", strings.ToUpper(r.Method), r.Path, r.MaxBodyBytes, responseName(r), r.ResponseFormat == "raw", i, name)
|
||||
} else {
|
||||
routes += fmt.Sprintf("httpx.HandleWithResponse(router,%q,%q,responseEncoder(%q,%t),h%d.%s", strings.ToUpper(r.Method), r.Path, responseName(r), r.ResponseFormat == "raw", i, name)
|
||||
}
|
||||
for _, m := range r.Middleware {
|
||||
routes += fmt.Sprintf(",deps.Middlewares[%q]", m)
|
||||
}
|
||||
routes += ")\n"
|
||||
if r.Manual {
|
||||
put(seeds, "internal/handler/"+group+"/"+lower(r.Handler)+"Manual.go", fmt.Sprintf("package %s\nimport(%q;apierrors %q)\n// %s owns raw/multipart binding and response output. h.deps holds project dependencies.\n// This file is preserved on regeneration.\nfunc(h *Handler)%s(c *httpx.Context)error{return apierrors.New(501,\"NOT_IMPLEMENTED\",\"manual handler is not implemented\")}\n", packageName, frameworkModule+"/httpx", frameworkModule+"/errors", name, name))
|
||||
continue
|
||||
}
|
||||
if r.Request != "" && !r.CustomBinding {
|
||||
scalarArgs := ""
|
||||
if len(c.Spec.Scalars) > 0 {
|
||||
scalarArgs = "types.ContractScalars()..."
|
||||
}
|
||||
text += fmt.Sprintf("var %sRequest = contract.MustNew[types.%s](%s)\n", lower(r.Handler), r.Request, scalarArgs)
|
||||
}
|
||||
text += fmt.Sprintf("func(h *Handler) %s(c *httpx.Context)error {\n", name)
|
||||
call := "c.Context()"
|
||||
if r.Request != "" {
|
||||
text += fmt.Sprintf("var req types.%s\nif err:=%sRequest.Bind(c.Request(),httpx.RouteParams(c.Context()),&req);err!=nil{return err}\n", r.Request, lower(r.Handler))
|
||||
if r.CustomBinding {
|
||||
text += fmt.Sprintf("var req types.%s\nif err:=h.bind%s(c,&req);err!=nil{return err}\n", r.Request, name)
|
||||
put(seeds, "internal/handler/"+group+"/"+lower(r.Handler)+"Bind.go", fmt.Sprintf("package %s\nimport(%q;%q;apierrors %q)\n// bind%s is project-owned; repeated generation preserves it.\nfunc(h *Handler)bind%s(c *httpx.Context,req *types.%s)error{return apierrors.New(501,\"BINDING_NOT_IMPLEMENTED\",\"custom binding is not implemented\")}\n", packageName, frameworkModule+"/httpx", o.Module+"/internal/types", frameworkModule+"/errors", name, name, r.Request))
|
||||
} else {
|
||||
limit := ""
|
||||
if r.MaxBodyBytes > 0 {
|
||||
limit = fmt.Sprintf(",%d", r.MaxBodyBytes)
|
||||
}
|
||||
text += fmt.Sprintf("var req types.%s\nif err:=%sRequest.Bind(c.Request(),httpx.RouteParams(c.Context()),&req%s);err!=nil{return err}\n", r.Request, lower(r.Handler), limit)
|
||||
}
|
||||
call += ", &req"
|
||||
}
|
||||
if r.Response != "" {
|
||||
@@ -392,11 +453,6 @@ func renderProject(o Options, c *Compiled, starter bool) (map[string][]byte, map
|
||||
} else {
|
||||
text += fmt.Sprintf("if err:=h.service.%s(%s);err!=nil{return err};return c.NoContent()\n}\n", name, call)
|
||||
}
|
||||
routes += fmt.Sprintf("httpx.HandleWithResponse(router,%q,%q,responseEncoder(%q,%t),h%d.%s", strings.ToUpper(r.Method), r.Path, responseName(r), r.ResponseFormat == "raw", i, name)
|
||||
for _, m := range r.Middleware {
|
||||
routes += fmt.Sprintf(",deps.Middlewares[%q]", m)
|
||||
}
|
||||
routes += ")\n"
|
||||
service := fmt.Sprintf("package %s\nimport(\"context\"; apierrors %q;", packageName, frameworkModule+"/errors")
|
||||
if r.Request != "" || r.Response != "" {
|
||||
service += fmt.Sprintf("%q;", o.Module+"/internal/types")
|
||||
@@ -417,6 +473,10 @@ func renderProject(o Options, c *Compiled, starter bool) (map[string][]byte, map
|
||||
}
|
||||
put(seeds, "internal/service/"+group+"/"+lower(r.Handler)+".go", service)
|
||||
}
|
||||
if !hasAutomatic {
|
||||
text = strings.Replace(text, strconv.Quote(frameworkModule+"/httpx")+";", "", 1)
|
||||
text = strings.Replace(text, "\"context\";", "", 1)
|
||||
}
|
||||
if !hasResponse(groupRoutes) {
|
||||
text = strings.Replace(text, "\"fmt\";", "", 1)
|
||||
}
|
||||
@@ -464,7 +524,7 @@ func renderProject(o Options, c *Compiled, starter bool) (map[string][]byte, map
|
||||
}
|
||||
func hasResponse(routes []Route) bool {
|
||||
for _, r := range routes {
|
||||
if r.Response != "" {
|
||||
if r.Response != "" && !r.Manual {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ type Spec struct {
|
||||
Errors []ErrorDefinition
|
||||
Auth []AuthDefinition
|
||||
Responses []ResponseDefinition
|
||||
Scalars []ScalarDefinition
|
||||
Types []Type
|
||||
Routes []Route
|
||||
Sources map[string][]byte // relative to the entry API's directory
|
||||
@@ -30,6 +31,9 @@ type Type struct {
|
||||
}
|
||||
type Field struct{ Name, Type, Tag string }
|
||||
type Route struct {
|
||||
Manual, CustomBinding bool
|
||||
BodyMode, Produces string
|
||||
MaxBodyBytes int64
|
||||
Method, Path, Request, Response, Handler, Group, Summary string
|
||||
Middleware []string
|
||||
Auth string
|
||||
@@ -199,6 +203,10 @@ func (p *parser) parse() error {
|
||||
syntaxSeen := false
|
||||
for p.skip(); p.tokens[p.at].kind != scanner.EOF; p.skip() {
|
||||
switch p.peek() {
|
||||
case "scalar":
|
||||
if err := p.parseScalar(); err != nil {
|
||||
return err
|
||||
}
|
||||
case "syntax":
|
||||
if syntaxSeen {
|
||||
return p.err("duplicate syntax")
|
||||
@@ -393,7 +401,15 @@ func (p *parser) parseType() error {
|
||||
}
|
||||
expression := ""
|
||||
for p.peek() != "\n" && p.peek() != ";" && p.peek() != "}" && p.tokens[p.at].kind != scanner.RawString && p.tokens[p.at].kind != scanner.EOF {
|
||||
expression += p.next().text
|
||||
if p.peek() == "interface" {
|
||||
p.next()
|
||||
if p.expect("{") != nil || p.expect("}") != nil {
|
||||
return p.err("only empty interface{} is supported; use any for dynamic JSON")
|
||||
}
|
||||
expression += "any"
|
||||
} else {
|
||||
expression += p.next().text
|
||||
}
|
||||
}
|
||||
if expression == "" {
|
||||
return p.err("field type required; embedded types are not supported")
|
||||
@@ -453,6 +469,28 @@ func (p *parser) parseService(server map[string]string) error {
|
||||
}
|
||||
seen[annotation] = true
|
||||
switch annotation {
|
||||
case "handlerMode":
|
||||
mode, err := p.ident()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if mode != "manual" {
|
||||
return p.err("handlerMode must be manual")
|
||||
}
|
||||
route.Manual = true
|
||||
case "binding":
|
||||
mode, err := p.ident()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if mode != "custom" {
|
||||
return p.err("binding must be custom")
|
||||
}
|
||||
route.CustomBinding = true
|
||||
case "produces":
|
||||
route.Produces, e = p.quoted()
|
||||
case "body":
|
||||
e = p.parseBody(&route)
|
||||
case "handler":
|
||||
route.Handler, e = p.ident()
|
||||
case "doc":
|
||||
@@ -512,7 +550,7 @@ func (p *parser) parseService(server map[string]string) error {
|
||||
if p.peek() != "\n" && p.peek() != ";" && p.peek() != "}" {
|
||||
return p.err("unexpected route suffix")
|
||||
}
|
||||
if route.Response == "" && !seen["status"] {
|
||||
if route.Response == "" && !seen["status"] && !route.Manual {
|
||||
route.Status = 204
|
||||
}
|
||||
p.spec.Routes = append(p.spec.Routes, route)
|
||||
|
||||
95
cmd/go-omni/apigen/requestOptions.go
Normal file
95
cmd/go-omni/apigen/requestOptions.go
Normal file
@@ -0,0 +1,95 @@
|
||||
package apigen
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"git.yuntuo.hk/k2safe/go-omni/contract"
|
||||
"mime"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func (p *parser) parseBody(r *Route) error {
|
||||
props, err := p.metadata()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for key, value := range props {
|
||||
switch key {
|
||||
case "mode":
|
||||
r.BodyMode = value
|
||||
case "maxBytes":
|
||||
r.MaxBodyBytes, err = strconv.ParseInt(value, 10, 64)
|
||||
if err != nil || r.MaxBodyBytes <= 0 || r.MaxBodyBytes > 1<<40 {
|
||||
return p.err("maxBytes must be 1..1099511627776 bytes")
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("unknown body property %s", key)
|
||||
}
|
||||
}
|
||||
if r.MaxBodyBytes == 0 {
|
||||
r.MaxBodyBytes = contract.DefaultMaxBodyBytes
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func validateRouteExtensions(r Route) error {
|
||||
if r.BodyMode != "" && r.BodyMode != "json" && r.BodyMode != "raw" && r.BodyMode != "multipart" {
|
||||
return errors.New("body mode must be json, raw or multipart")
|
||||
}
|
||||
if (r.BodyMode == "raw" || r.BodyMode == "multipart") && !r.Manual {
|
||||
return errors.New("raw/multipart body requires @handlerMode manual")
|
||||
}
|
||||
if r.CustomBinding && (r.Manual || r.Request == "") {
|
||||
return errors.New("@binding custom requires an automatic handler with a request DTO")
|
||||
}
|
||||
if r.MaxBodyBytes > 0 && (r.Method == "get" || r.Method == "head") {
|
||||
return errors.New("GET/HEAD cannot declare a body limit")
|
||||
}
|
||||
if r.Produces != "" {
|
||||
if !r.Manual {
|
||||
return errors.New("@produces requires @handlerMode manual")
|
||||
}
|
||||
media, params, err := mime.ParseMediaType(r.Produces)
|
||||
if err != nil || len(params) != 0 || media != r.Produces || strings.Contains(media, "*") {
|
||||
return errors.New("produces requires a concrete media type without parameters")
|
||||
}
|
||||
if r.Response != "" || r.Status == 204 || r.Method == "head" {
|
||||
return errors.New("@produces uses a manual response without a DTO, 204 or HEAD")
|
||||
}
|
||||
}
|
||||
if r.Manual && r.Status == 204 && r.Response != "" {
|
||||
return errors.New("204 cannot declare a response")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func decorateRequestOptions(op map[string]any, r Route) {
|
||||
if r.Manual {
|
||||
op["x-omni-handler-mode"] = "manual"
|
||||
}
|
||||
if r.CustomBinding {
|
||||
op["x-omni-binding"] = "custom"
|
||||
}
|
||||
if r.MaxBodyBytes > 0 {
|
||||
op["x-omni-max-body-bytes"] = r.MaxBodyBytes
|
||||
}
|
||||
if r.BodyMode == "raw" || r.BodyMode == "multipart" {
|
||||
media := "application/octet-stream"
|
||||
schema := map[string]any{"type": "string", "format": "binary"}
|
||||
if r.BodyMode == "multipart" {
|
||||
media = "multipart/form-data"
|
||||
schema = map[string]any{"type": "object", "additionalProperties": true}
|
||||
}
|
||||
op["requestBody"] = map[string]any{"required": true, "content": map[string]any{media: map[string]any{"schema": schema}}}
|
||||
}
|
||||
if r.Produces != "" {
|
||||
schema := map[string]any{"type": "string"}
|
||||
if r.Produces == "application/octet-stream" {
|
||||
schema["format"] = "binary"
|
||||
}
|
||||
if r.Produces == "application/json" {
|
||||
schema = map[string]any{}
|
||||
}
|
||||
op["responses"].(map[string]any)[strconv.Itoa(r.Status)] = map[string]any{"description": "Success", "content": map[string]any{r.Produces: map[string]any{"schema": schema}}}
|
||||
}
|
||||
}
|
||||
74
cmd/go-omni/apigen/scalar.go
Normal file
74
cmd/go-omni/apigen/scalar.go
Normal file
@@ -0,0 +1,74 @@
|
||||
package apigen
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"git.yuntuo.hk/k2safe/go-omni/contract"
|
||||
"golang.org/x/mod/module"
|
||||
"reflect"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type ScalarDefinition struct {
|
||||
Name, GoImport, GoType, JSONInput, JSONOutput, Position string
|
||||
Text bool
|
||||
}
|
||||
|
||||
func (p *parser) parseScalar() error {
|
||||
pos := p.next().position
|
||||
name, err := p.ident()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p.skip()
|
||||
props, err := p.metadata()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d := ScalarDefinition{Name: name, Position: pos}
|
||||
for key, value := range props {
|
||||
switch key {
|
||||
case "goImport":
|
||||
d.GoImport = value
|
||||
case "goType":
|
||||
d.GoType = value
|
||||
case "jsonInput":
|
||||
d.JSONInput = value
|
||||
case "jsonOutput":
|
||||
d.JSONOutput = value
|
||||
case "text":
|
||||
if value != "true" && value != "false" {
|
||||
return p.err("text must be true or false")
|
||||
}
|
||||
d.Text = value == "true"
|
||||
default:
|
||||
return fmt.Errorf("%s: unknown scalar property %s", pos, key)
|
||||
}
|
||||
}
|
||||
p.spec.Scalars = append(p.spec.Scalars, d)
|
||||
return nil
|
||||
}
|
||||
func compileScalars(spec *Spec, types map[string]Type) (map[string]reflect.Type, []contract.Scalar, error) {
|
||||
out := map[string]reflect.Type{}
|
||||
var defs []contract.Scalar
|
||||
goTypes := map[string]bool{}
|
||||
for _, d := range spec.Scalars {
|
||||
key := d.GoImport + "." + d.GoType
|
||||
if d.Name == "ContractScalars" || !exportedName.MatchString(d.Name) || !exportedName.MatchString(d.GoType) || out[d.Name] != nil || types[d.Name].Name != "" || goTypes[key] {
|
||||
return nil, nil, fmt.Errorf("%s: scalar names and Go types must be unique; names must be UpperCamelCase", d.Position)
|
||||
}
|
||||
if err := module.CheckImportPath(d.GoImport); err != nil || strings.Contains(d.GoImport, "\\") {
|
||||
return nil, nil, fmt.Errorf("%s: invalid scalar goImport", d.Position)
|
||||
}
|
||||
// Unique stand-in types allow CLI schema checks without executing project code.
|
||||
t := reflect.StructOf([]reflect.StructField{{Name: d.Name, Type: reflect.TypeOf(false)}})
|
||||
def := contract.Scalar{Type: t, JSONInput: d.JSONInput, JSONOutput: d.JSONOutput, Text: d.Text}
|
||||
probe := reflect.StructOf([]reflect.StructField{{Name: "Value", Type: t, Tag: `json:"value"`}})
|
||||
if _, err := contract.Describe(probe, def); err != nil {
|
||||
return nil, nil, fmt.Errorf("%s: %w", d.Position, err)
|
||||
}
|
||||
out[d.Name] = t
|
||||
defs = append(defs, def)
|
||||
goTypes[key] = true
|
||||
}
|
||||
return out, defs, nil
|
||||
}
|
||||
117
cmd/go-omni/apigen/testdata/compatibility/consumer_test.go
vendored
Normal file
117
cmd/go-omni/apigen/testdata/compatibility/consumer_test.go
vendored
Normal file
@@ -0,0 +1,117 @@
|
||||
package compatibility_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"example.com/compatibility/internal/handler"
|
||||
"example.com/compatibility/internal/servicecontext"
|
||||
omni "git.yuntuo.hk/k2safe/go-omni"
|
||||
"git.yuntuo.hk/k2safe/go-omni/logx"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGeneratedCompatibility(t *testing.T) {
|
||||
logger, err := logx.New(logx.Config{Writer: io.Discard})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer logger.Close()
|
||||
deps, err := servicecontext.New(context.Background(), logger)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer deps.Close()
|
||||
app := omni.New()
|
||||
defer app.Close()
|
||||
if err = handler.RegisterRoutes(app, deps); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
send := func(method, path, body, contentType string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
r.Header.Set("Content-Type", contentType)
|
||||
w := httptest.NewRecorder()
|
||||
app.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
for _, id := range []string{`9223372036854775807`, `"9223372036854775807"`} {
|
||||
w := send("POST", "/echo", `{"id":`+id+`,"data":{"n":9223372036854775807}}`, "application/json")
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), `"id":"9223372036854775807"`) || !strings.Contains(w.Body.String(), `"n":9223372036854775807`) {
|
||||
t.Fatalf("scalar/dynamic: %d %s", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
for _, body := range []string{`{"id":true,"data":null}`, `{"id":9223372036854775808,"data":null}`, `{"id":1,"data":{"x":1,"x":2}}`, `{"id":1,"data":null,"extra":1}`} {
|
||||
if w := send("POST", "/echo", body, "application/json"); w.Code != 400 {
|
||||
t.Fatalf("accepted %s: %d", body, w.Code)
|
||||
}
|
||||
}
|
||||
payload := `{"id":1,"data":"` + strings.Repeat("x", (1<<20)+1) + `"}`
|
||||
if w := send("POST", "/echo", payload, "application/json"); w.Code != 200 {
|
||||
t.Fatalf("route limit not passed to Binder: %d", w.Code)
|
||||
}
|
||||
if w := send("POST", "/echo", `{"id":1,"data":"`+strings.Repeat("x", 2<<20)+`"}`, "application/json"); w.Code != 413 {
|
||||
t.Fatalf("large JSON: %d", w.Code)
|
||||
}
|
||||
if w := send("GET", "/items/9223372036854775807", "", ""); w.Code != 200 || !strings.Contains(w.Body.String(), `"id":"9223372036854775807"`) {
|
||||
t.Fatalf("text scalar: %d %s", w.Code, w.Body)
|
||||
}
|
||||
if w := send("POST", "/custom", `{"value":"hello"}`, "application/json"); w.Code != 200 || !strings.Contains(w.Body.String(), "HELLO") {
|
||||
t.Fatalf("custom binder: %d %s", w.Code, w.Body)
|
||||
}
|
||||
raw := `{ "event": 1, "id": "original bytes" }`
|
||||
mac := hmac.New(sha256.New, []byte("fixture-only-key"))
|
||||
mac.Write([]byte(raw))
|
||||
r := httptest.NewRequest("POST", "/callback", strings.NewReader(raw))
|
||||
r.Header.Set("X-Signature", hex.EncodeToString(mac.Sum(nil)))
|
||||
w := httptest.NewRecorder()
|
||||
app.ServeHTTP(w, r)
|
||||
if w.Code != 200 || w.Body.String() != "accepted" {
|
||||
t.Fatalf("raw callback: %d %s", w.Code, w.Body)
|
||||
}
|
||||
r = httptest.NewRequest("POST", "/callback", strings.NewReader(strings.Repeat("x", 129)))
|
||||
r.ContentLength = -1
|
||||
w = httptest.NewRecorder()
|
||||
app.ServeHTTP(w, r)
|
||||
if w.Code != 413 {
|
||||
t.Fatalf("chunked body limit: %d %s", w.Code, w.Body)
|
||||
}
|
||||
temp := t.TempDir()
|
||||
t.Setenv("TMPDIR", temp)
|
||||
var form bytes.Buffer
|
||||
writer := multipart.NewWriter(&form)
|
||||
part, err := writer.CreateFormFile("file", "sample.bin")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
part.Write(bytes.Repeat([]byte("x"), 8192))
|
||||
writer.Close()
|
||||
w = send("POST", "/upload", form.String(), writer.FormDataContentType())
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), `"bytes":8192`) {
|
||||
t.Fatalf("upload: %d %s", w.Code, w.Body)
|
||||
}
|
||||
entries, err := os.ReadDir(temp)
|
||||
if err != nil || len(entries) != 0 {
|
||||
t.Fatalf("multipart temp files leaked: %v %v", entries, err)
|
||||
}
|
||||
w = send("GET", "/download", "", "")
|
||||
if w.Code != 200 || w.Body.Len() != 128<<10 || w.Header().Get("Content-Disposition") == "" {
|
||||
t.Fatalf("download wrapped: %d %d", w.Code, w.Body.Len())
|
||||
}
|
||||
var doc map[string]any
|
||||
if err = json.Unmarshal([]byte(handler.OpenAPIDocument), &doc); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
paths := doc["paths"].(map[string]any)
|
||||
media := paths["/download"].(map[string]any)["get"].(map[string]any)["responses"].(map[string]any)["200"].(map[string]any)["content"].(map[string]any)
|
||||
if media["application/octet-stream"] == nil || media["application/json"] != nil {
|
||||
t.Fatal("download schema is JSON")
|
||||
}
|
||||
}
|
||||
16
cmd/go-omni/apigen/testdata/compatibility/download.go
vendored
Normal file
16
cmd/go-omni/apigen/testdata/compatibility/download.go
vendored
Normal file
@@ -0,0 +1,16 @@
|
||||
package files
|
||||
|
||||
import (
|
||||
"git.yuntuo.hk/k2safe/go-omni/httpx"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func (h *Handler) Download(c *httpx.Context) error {
|
||||
return httpx.WrapHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/octet-stream")
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="demo.bin"`)
|
||||
_, _ = io.Copy(w, strings.NewReader(strings.Repeat("x", 128<<10)))
|
||||
}))(c)
|
||||
}
|
||||
16
cmd/go-omni/apigen/testdata/compatibility/echo.go
vendored
Normal file
16
cmd/go-omni/apigen/testdata/compatibility/echo.go
vendored
Normal file
@@ -0,0 +1,16 @@
|
||||
package demo
|
||||
|
||||
import (
|
||||
"context"
|
||||
"example.com/compatibility/internal/types"
|
||||
)
|
||||
|
||||
func (s *Service) Echo(ctx context.Context, req *types.EchoReq) (*types.EchoResp, error) {
|
||||
return &types.EchoResp{ID: req.ID, Data: req.Data}, nil
|
||||
}
|
||||
func (s *Service) Item(ctx context.Context, req *types.ItemReq) (*types.EchoResp, error) {
|
||||
return &types.EchoResp{ID: req.ID, Data: map[string]any{"found": true}}, nil
|
||||
}
|
||||
func (s *Service) Custom(ctx context.Context, req *types.CustomReq) (*types.CustomResp, error) {
|
||||
return &types.CustomResp{Value: req.Value}, nil
|
||||
}
|
||||
58
cmd/go-omni/apigen/testdata/compatibility/hooks.go
vendored
Normal file
58
cmd/go-omni/apigen/testdata/compatibility/hooks.go
vendored
Normal file
@@ -0,0 +1,58 @@
|
||||
package demo
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"example.com/compatibility/internal/types"
|
||||
apierrors "git.yuntuo.hk/k2safe/go-omni/errors"
|
||||
"git.yuntuo.hk/k2safe/go-omni/httpx"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func (h *Handler) bindCustom(c *httpx.Context, req *types.CustomReq) error {
|
||||
decoder := json.NewDecoder(c.Request().Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(req); err != nil {
|
||||
return apierrors.BadRequest("INVALID_REQUEST", "invalid request").WithCause(err)
|
||||
}
|
||||
var extra any
|
||||
if err := decoder.Decode(&extra); err != io.EOF {
|
||||
return apierrors.BadRequest("INVALID_REQUEST", "one JSON value required").WithCause(err)
|
||||
}
|
||||
req.Value = strings.ToUpper(req.Value)
|
||||
return nil
|
||||
}
|
||||
func (h *Handler) Upload(c *httpx.Context) error {
|
||||
// The small memory threshold deliberately exercises disk spill and cleanup.
|
||||
if err := c.Request().ParseMultipartForm(8); err != nil {
|
||||
return err
|
||||
}
|
||||
file, _, err := c.Request().FormFile("file")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
count, err := io.Copy(io.Discard, file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return c.OK(map[string]any{"bytes": count})
|
||||
}
|
||||
func (h *Handler) Callback(c *httpx.Context) error {
|
||||
raw, err := io.ReadAll(c.Request().Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// This fixed key belongs only to the test fixture. Applications inject secrets.
|
||||
mac := hmac.New(sha256.New, []byte("fixture-only-key"))
|
||||
mac.Write(raw)
|
||||
signature, err := hex.DecodeString(c.Header("X-Signature"))
|
||||
if err != nil || !hmac.Equal(signature, mac.Sum(nil)) {
|
||||
return c.Text(http.StatusUnauthorized, "invalid signature")
|
||||
}
|
||||
return c.Text(http.StatusOK, "accepted")
|
||||
}
|
||||
@@ -252,7 +252,7 @@ func apply(root, module, entry string, generated, seeds map[string][]byte, check
|
||||
}
|
||||
func digest(data []byte) string { sum := sha256.Sum256(data); return hex.EncodeToString(sum[:]) }
|
||||
func ownedPath(name string) bool {
|
||||
if name == "internal/handler/responseGen.go" {
|
||||
if name == "internal/handler/responseGen.go" || name == "internal/types/scalarsGen.go" {
|
||||
return true
|
||||
}
|
||||
if name == "internal/apierrors/errorsGen.go" || name == "docs/openapi.json" || name == "internal/types/typesGen.go" || name == "internal/handler/routesGen.go" || name == "internal/handler/openapiGen.go" || name == "internal/middleware/registryGen.go" {
|
||||
|
||||
@@ -10,7 +10,7 @@ const frameworkModule = "git.yuntuo.hk/k2safe/go-omni"
|
||||
// Source builds can carry an unpublished VCS version (including +dirty).
|
||||
// Keep this fallback in sync with the next release; installed CLIs use their
|
||||
// downloaded module version, which also has a module checksum.
|
||||
const defaultFrameworkVersion = "v0.8.0-preview"
|
||||
const defaultFrameworkVersion = "v0.9.0-preview"
|
||||
|
||||
// This target is not a claim that the release already exists. Source users
|
||||
// select a local framework checkout until the module templates are published.
|
||||
|
||||
Reference in New Issue
Block a user