feat: add HTTP migration bridges and extensible API binding
This commit is contained in:
29
examples/compatibility/ids/id.go
Normal file
29
examples/compatibility/ids/id.go
Normal file
@@ -0,0 +1,29 @@
|
||||
// Package ids demonstrates an application-owned scalar. The framework does not
|
||||
// impose this ID policy on any other type or project.
|
||||
package ids
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type ID int64
|
||||
|
||||
func (id ID) MarshalJSON() ([]byte, error) { return json.Marshal(strconv.FormatInt(int64(id), 10)) }
|
||||
func (id *ID) UnmarshalJSON(raw []byte) error {
|
||||
value := string(raw)
|
||||
if len(raw) > 0 && raw[0] == '"' {
|
||||
if err := json.Unmarshal(raw, &value); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return id.UnmarshalText([]byte(value))
|
||||
}
|
||||
func (id *ID) UnmarshalText(raw []byte) error {
|
||||
value, err := strconv.ParseInt(string(raw), 10, 64)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*id = ID(value)
|
||||
return nil
|
||||
}
|
||||
75
examples/compatibility/main.go
Normal file
75
examples/compatibility/main.go
Normal file
@@ -0,0 +1,75 @@
|
||||
// This example only uses local HTTP and bounded streaming; it has no database.
|
||||
package main
|
||||
|
||||
import (
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
omni "git.yuntuo.hk/k2safe/go-omni"
|
||||
"git.yuntuo.hk/k2safe/go-omni/contract"
|
||||
"git.yuntuo.hk/k2safe/go-omni/examples/compatibility/ids"
|
||||
"git.yuntuo.hk/k2safe/go-omni/httpx"
|
||||
)
|
||||
|
||||
type echoRequest struct {
|
||||
ID ids.ID `json:"id"`
|
||||
Data any `json:"data"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
app := omni.New(omni.WithLogger(true))
|
||||
defer app.Close()
|
||||
app.Use(httpx.WrapMiddleware(func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-Example", "compatibility")
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}))
|
||||
app.GET("/legacy", httpx.WrapHandler(http.HandlerFunc(http.NotFound)))
|
||||
binder := contract.MustNew[echoRequest](contract.ScalarOf[ids.ID]("string|int64", "string", true))
|
||||
app.POST("/echo", func(c *httpx.Context) error {
|
||||
var req echoRequest
|
||||
if err := binder.Bind(c.Request(), nil, &req); err != nil {
|
||||
return err
|
||||
}
|
||||
return c.OK(req)
|
||||
})
|
||||
app.HandleWithBodyLimit("POST", "/upload", 10<<20, nil, func(c *httpx.Context) error {
|
||||
reader, err := c.Request().MultipartReader()
|
||||
if err != nil {
|
||||
return omni.BadRequest("INVALID_MULTIPART", "multipart body required")
|
||||
}
|
||||
var total int64
|
||||
for {
|
||||
part, err := reader.NextPart()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Replace io.Discard with a streaming storage writer. Do not trust file names
|
||||
// as filesystem paths. io.Copy never buffers the complete uploaded file.
|
||||
n, copyErr := io.Copy(io.Discard, part)
|
||||
closeErr := part.Close()
|
||||
if copyErr != nil {
|
||||
return copyErr
|
||||
}
|
||||
if closeErr != nil {
|
||||
return closeErr
|
||||
}
|
||||
total += n
|
||||
}
|
||||
return c.OK(map[string]int64{"bytes": total})
|
||||
})
|
||||
app.GET("/download", 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="example.txt"`)
|
||||
_, _ = io.Copy(w, strings.NewReader("A standard Handler keeps its original download response.\n"))
|
||||
})))
|
||||
if err := app.Run("127.0.0.1:8080"); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
64
examples/contracts/compatibility.api
Normal file
64
examples/contracts/compatibility.api
Normal file
@@ -0,0 +1,64 @@
|
||||
syntax = "v1"
|
||||
|
||||
scalar BusinessID (
|
||||
goImport: "git.yuntuo.hk/k2safe/go-omni/examples/compatibility/ids"
|
||||
goType: ID
|
||||
jsonInput: string | int64
|
||||
jsonOutput: string
|
||||
text: true
|
||||
)
|
||||
|
||||
type EchoReq {
|
||||
ID BusinessID `json:"id"`
|
||||
Data any `json:"data"`
|
||||
Legacy interface{} `json:"legacy,optional"`
|
||||
}
|
||||
type EchoResp {
|
||||
ID BusinessID `json:"id"`
|
||||
Data any `json:"data"`
|
||||
}
|
||||
type ItemReq {
|
||||
ID BusinessID `path:"id"`
|
||||
}
|
||||
type CustomReq {
|
||||
Value string `json:"value"`
|
||||
}
|
||||
type CustomResp {
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
@server (group: demo)
|
||||
service compatibility-api {
|
||||
@body (maxBytes: 2097152)
|
||||
@handler echo
|
||||
post /echo (EchoReq) returns (EchoResp)
|
||||
|
||||
@handler item
|
||||
get /items/:id (ItemReq) returns (EchoResp)
|
||||
|
||||
@binding custom
|
||||
@body (maxBytes: 512)
|
||||
@handler custom
|
||||
post /custom (CustomReq) returns (CustomResp)
|
||||
|
||||
@handlerMode manual
|
||||
@body (mode: multipart
|
||||
maxBytes: 65536)
|
||||
@handler upload
|
||||
post /upload
|
||||
|
||||
@handlerMode manual
|
||||
@body (mode: raw
|
||||
maxBytes: 128)
|
||||
@produces "text/plain"
|
||||
@handler callback
|
||||
post /callback
|
||||
}
|
||||
|
||||
@server (group: files)
|
||||
service compatibility-api {
|
||||
@handlerMode manual
|
||||
@produces "application/octet-stream"
|
||||
@handler download
|
||||
get /download
|
||||
}
|
||||
@@ -13,8 +13,8 @@
|
||||
"internal/apierrors/errorsGen.go": "20e94bbc90ae9f4330de4c25b9a550026c4c352502719a643ede3e8912a6566e",
|
||||
"internal/handler/openapiGen.go": "e4130f5c7494f7db4830bfef203fa8154a9cd087c95954f64c29d74693ead433",
|
||||
"internal/handler/responseGen.go": "d742efc2a3d1d168fae7849e905297bd440c3d6b3802b6150f494c07e6097f4f",
|
||||
"internal/handler/routesGen.go": "0ff429a8aa7f8643e0e844f7c43a63a1f82cca5ce6bfe917f06edd860ebe923f",
|
||||
"internal/handler/user/handlersGen.go": "06f3c2798ff323812ff3eb2d8b933a569af3ce1b86a67b66036374add98c0d7e",
|
||||
"internal/handler/routesGen.go": "4e0c6879cea40e9c0155439fa1fce2cd19b5f83ea6e304523c41f8dc9c3a28e0",
|
||||
"internal/handler/user/handlersGen.go": "1808afc8e4e8ca9785a8552eff64fad39bd5fe4e6e92971f35afc9006e23d76e",
|
||||
"internal/middleware/registryGen.go": "a6122a5453dedc6a4415860108814c50e155128cfe5412b39dd33ce2d01b4b00",
|
||||
"internal/types/typesGen.go": "3ab2ce9ffe467c3ea53ac3d1fec283ecebc87cef57fd592d08dca991fd964876"
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ func RegisterRoutes(router openapi.Registrar, deps *servicecontext.Context) erro
|
||||
if deps.Middlewares["Auth"] == nil {
|
||||
return fmt.Errorf("missing middleware Auth")
|
||||
}
|
||||
h0 := h0.New(s0.New(deps))
|
||||
h0 := h0.New(s0.New(deps), deps)
|
||||
httpx.HandleWithResponse(router, "POST", "/api/v1/users", responseEncoder("", false), h0.CreateUser, deps.Middlewares["Auth"])
|
||||
httpx.HandleWithResponse(router, "GET", "/api/v1/users/:id", responseEncoder("", false), h0.GetUser, deps.Middlewares["Auth"])
|
||||
httpx.HandleWithResponse(router, "GET", "/api/v1/users", responseEncoder("", false), h0.ListUsers, deps.Middlewares["Auth"])
|
||||
|
||||
@@ -3,6 +3,7 @@ package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"example.com/userService/internal/servicecontext"
|
||||
"example.com/userService/internal/types"
|
||||
"fmt"
|
||||
"git.yuntuo.hk/k2safe/go-omni/contract"
|
||||
@@ -17,9 +18,18 @@ type Service interface {
|
||||
DeleteUser(ctx context.Context, req *types.UserIDReq) error
|
||||
ExportUser(ctx context.Context, req *types.UserIDReq) (*types.ExportResp, error)
|
||||
}
|
||||
type Handler struct{ service Service }
|
||||
type Handler struct {
|
||||
service Service
|
||||
deps *servicecontext.Context
|
||||
}
|
||||
|
||||
func New(s Service) *Handler { return &Handler{service: s} }
|
||||
func New(s Service, deps ...*servicecontext.Context) *Handler {
|
||||
h := &Handler{service: s}
|
||||
if len(deps) > 0 {
|
||||
h.deps = deps[0]
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
var createUserRequest = contract.MustNew[types.CreateUserReq]()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user