83 lines
2.4 KiB
Go
83 lines
2.4 KiB
Go
package demo
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"io"
|
|
"strings"
|
|
|
|
"example.com/managed/internal/svc"
|
|
"example.com/managed/internal/types"
|
|
omnierrors "git.yuntuo.hk/k2safe/go-omni/errors"
|
|
"git.yuntuo.hk/k2safe/go-omni/httpx"
|
|
)
|
|
|
|
func (l *Logic) Check(ctx context.Context, req *types.CheckReq) (*types.Receipt, error) {
|
|
switch req.Kind {
|
|
case "fixed":
|
|
return nil, omnierrors.ByCode("INVALID")
|
|
case "params":
|
|
return nil, omnierrors.ByCode("TOO_LONG").WithParams(map[string]any{"label": "企业名称", "max": 100})
|
|
case "unknown":
|
|
return nil, omnierrors.ByCode("UNKNOWN").WithCause(errors.New("private cause"))
|
|
}
|
|
return &types.Receipt{Bytes: 42}, nil
|
|
}
|
|
func (l *Logic) Other(ctx context.Context, req *types.CheckReq) (*types.Receipt, error) {
|
|
return l.Check(ctx, req)
|
|
}
|
|
func (l *Logic) RawJSON(context.Context) (*types.Receipt, error) {
|
|
return &types.Receipt{Bytes: 3}, nil
|
|
}
|
|
func (l *Logic) Upload(ctx context.Context, body *httpx.Body) (*types.Receipt, error) {
|
|
var total int64
|
|
for {
|
|
part, err := body.Parts.NextPart()
|
|
if err == io.EOF {
|
|
break
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
n, err := io.Copy(io.Discard, part)
|
|
closeErr := part.Close()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if closeErr != nil {
|
|
return nil, closeErr
|
|
}
|
|
total += n
|
|
}
|
|
return &types.Receipt{Bytes: total}, nil
|
|
}
|
|
func (l *Logic) Callback(ctx context.Context, body *httpx.Body) (*httpx.Stream, error) {
|
|
// The route's 64-byte limit bounds this example's memory use. A real signature
|
|
// implementation can hash body.Raw incrementally and authenticate its headers.
|
|
data, err := io.ReadAll(body.Raw)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if body.Header.Get("X-Signature") != "valid" {
|
|
return nil, omnierrors.ByCode("INVALID")
|
|
}
|
|
return &httpx.Stream{Content: io.NopCloser(strings.NewReader("ACK:" + string(data)))}, nil
|
|
}
|
|
func (l *Logic) Download(context.Context) (*httpx.Stream, error) {
|
|
return &httpx.Stream{Content: &countedReader{Reader: strings.NewReader("file-content")}, Name: "测试.txt"}, nil
|
|
}
|
|
|
|
type countedReader struct{ io.Reader }
|
|
|
|
func (c *countedReader) Close() error { svc.DownloadClosed.Add(1); return nil }
|
|
func (l *Logic) Slow(context.Context) (*types.Receipt, error) {
|
|
defer svc.SlowReturned.Add(1)
|
|
before := svc.Closed.Load()
|
|
svc.Started <- struct{}{}
|
|
<-svc.Release
|
|
if svc.Closed.Load() != before {
|
|
return nil, errors.New("dependency closed before drain")
|
|
}
|
|
return &types.Receipt{Bytes: 1}, nil
|
|
}
|