feat: complete contract-driven business development and MySQL integration
This commit is contained in:
@@ -1,14 +1,11 @@
|
||||
// Package settings owns this project's configuration; it adds no business identity model.
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"git.yuntuo.hk/k2safe/go-omni/config"
|
||||
"git.yuntuo.hk/k2safe/go-omni/logx"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.yuntuo.hk/k2safe/go-omni/config"
|
||||
"git.yuntuo.hk/k2safe/go-omni/logx"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
@@ -26,44 +23,40 @@ func Default() Config {
|
||||
return Config{Server: server}
|
||||
}
|
||||
|
||||
// Load uses defaults -> strict YAML/JSON -> nonempty environment variables.
|
||||
// Pass an empty path to use only defaults and environment.
|
||||
// Load applies defaults -> file -> typed environment -> validation.
|
||||
// New fields automatically use GO_OMNI_<JSON_PATH>, or an explicit env tag.
|
||||
func Load(path string) (Config, error) {
|
||||
cfg := Default()
|
||||
var err error
|
||||
cfg, err = config.ApplyDefaults(cfg)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
if path != "" {
|
||||
cfg, err = config.DecodeFile(path, cfg)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
}
|
||||
cfg, err = config.OverlayEnv(cfg, config.EnvOptions{Prefix: "GO_OMNI_"})
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
// Preserve the documented framework aliases (HTTP_ADDR, LOG_LEVEL, etc).
|
||||
cfg.Server, err = config.ApplyEnv(cfg.Server, "")
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
// A stream explicitly selected by environment overrides a file profile.
|
||||
if output := strings.TrimSpace(os.Getenv("GO_OMNI_LOG_OUTPUT")); output != "" && strings.TrimSpace(os.Getenv("GO_OMNI_LOG_FILE")) == "" {
|
||||
cfg.Server.Log.File = ""
|
||||
cfg.Server.Log.Rotation = logx.RotationConfig{}
|
||||
}
|
||||
|
||||
if err = cfg.Validate(); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
return cfg, nil
|
||||
return cfg, cfg.Validate()
|
||||
}
|
||||
func (c Config) Validate() error {
|
||||
|
||||
if err := c.Server.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
if c.Server.Log.Format != "json" && c.Server.Log.Format != "text" {
|
||||
return errors.New("log.format must be json or text")
|
||||
}
|
||||
switch strings.ToLower(c.Server.Log.Level) {
|
||||
case "debug", "info", "warn", "warning", "error":
|
||||
default:
|
||||
return errors.New("invalid log.level")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ package handler
|
||||
import (
|
||||
"fmt"
|
||||
omni "git.yuntuo.hk/k2safe/go-omni"
|
||||
"git.yuntuo.hk/k2safe/go-omni/contract"
|
||||
|
||||
"example.com/managed/internal/svc"
|
||||
"git.yuntuo.hk/k2safe/go-omni/config"
|
||||
@@ -16,11 +17,13 @@ func NewApp(deps *svc.ServiceContext) (*omni.App, error) {
|
||||
return nil, fmt.Errorf("service context and lifecycle controller required; see PROJECT.md upgrade instructions")
|
||||
}
|
||||
cfg := deps.Config.Server
|
||||
cfg.LogInstance = deps.Logger
|
||||
for _, option := range deps.AppOptions() {
|
||||
if option != nil {
|
||||
option(&cfg)
|
||||
}
|
||||
}
|
||||
cfg.Request = contract.MergePolicy(cfg.Request, contract.RequestPolicy{UnknownQuery: "", UTF8: "", Charset: "", Body: ""})
|
||||
cfg.Response = newResponseTemplate("{\"body\":null,\"errorBody\":null,\"messageField\":\"msg\",\"requestIdField\":\"-\",\"codeType\":\"int32\",\"successCode\":0,\"errorCode\":9999,\"dataMode\":\"always\"}").Config()
|
||||
cfg.ResponseEncoder = nil
|
||||
if err := cfg.Validate(); err != nil {
|
||||
|
||||
@@ -36,7 +36,7 @@ var checkRequest = contract.MustNew[types.CheckReq]()
|
||||
|
||||
func (h *Handler) Check(c *httpx.Context) error {
|
||||
var req types.CheckReq
|
||||
if err := checkRequest.Bind(c.Request(), httpx.RouteParams(c.Context()), &req); err != nil {
|
||||
if err := checkRequest.BindWithPolicy(c.Request(), httpx.RouteParams(c.Context()), &req, contract.RequestPolicy{UnknownQuery: "", UTF8: "", Charset: "", Body: ""}); err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := h.logic.Check(c.Context(), &req)
|
||||
@@ -53,7 +53,7 @@ var otherRequest = contract.MustNew[types.CheckReq]()
|
||||
|
||||
func (h *Handler) Other(c *httpx.Context) error {
|
||||
var req types.CheckReq
|
||||
if err := otherRequest.Bind(c.Request(), httpx.RouteParams(c.Context()), &req); err != nil {
|
||||
if err := otherRequest.BindWithPolicy(c.Request(), httpx.RouteParams(c.Context()), &req, contract.RequestPolicy{UnknownQuery: "", UTF8: "", Charset: "", Body: ""}); err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := h.logic.Other(c.Context(), &req)
|
||||
@@ -65,7 +65,13 @@ func (h *Handler) Other(c *httpx.Context) error {
|
||||
}
|
||||
return c.OK(resp)
|
||||
}
|
||||
|
||||
var rawJSONRequest = contract.MustNew[struct{}]()
|
||||
|
||||
func (h *Handler) RawJSON(c *httpx.Context) error {
|
||||
if err := rawJSONRequest.BindWithPolicy(c.Request(), httpx.RouteParams(c.Context()), &struct{}{}, contract.RequestPolicy{UnknownQuery: "", UTF8: "", Charset: "", Body: ""}); err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := h.logic.RawJSON(c.Context())
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -75,7 +81,13 @@ func (h *Handler) RawJSON(c *httpx.Context) error {
|
||||
}
|
||||
return c.OK(resp)
|
||||
}
|
||||
|
||||
var uploadRequest = contract.MustNew[struct{}]()
|
||||
|
||||
func (h *Handler) Upload(c *httpx.Context) error {
|
||||
if err := uploadRequest.BindWithPolicy(c.Request(), httpx.RouteParams(c.Context()), &struct{}{}, contract.RequestPolicy{UnknownQuery: "", UTF8: "", Charset: "", Body: "auto"}, 2048); err != nil {
|
||||
return err
|
||||
}
|
||||
body, err := httpx.NewBody(c.Request(), "multipart")
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -92,7 +104,13 @@ func (h *Handler) Upload(c *httpx.Context) error {
|
||||
}
|
||||
return c.OK(resp)
|
||||
}
|
||||
|
||||
var callbackRequest = contract.MustNew[struct{}]()
|
||||
|
||||
func (h *Handler) Callback(c *httpx.Context) error {
|
||||
if err := callbackRequest.BindWithPolicy(c.Request(), httpx.RouteParams(c.Context()), &struct{}{}, contract.RequestPolicy{UnknownQuery: "", UTF8: "", Charset: "", Body: "auto"}, 64); err != nil {
|
||||
return err
|
||||
}
|
||||
body, err := httpx.NewBody(c.Request(), "raw")
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -112,7 +130,13 @@ func (h *Handler) Callback(c *httpx.Context) error {
|
||||
}
|
||||
return c.WriteStream(200, "text/plain", resp)
|
||||
}
|
||||
|
||||
var downloadRequest = contract.MustNew[struct{}]()
|
||||
|
||||
func (h *Handler) Download(c *httpx.Context) error {
|
||||
if err := downloadRequest.BindWithPolicy(c.Request(), httpx.RouteParams(c.Context()), &struct{}{}, contract.RequestPolicy{UnknownQuery: "", UTF8: "", Charset: "", Body: ""}); err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := h.logic.Download(c.Context())
|
||||
if err != nil {
|
||||
if resp != nil {
|
||||
@@ -122,7 +146,13 @@ func (h *Handler) Download(c *httpx.Context) error {
|
||||
}
|
||||
return c.WriteStream(200, "application/octet-stream", resp)
|
||||
}
|
||||
|
||||
var slowRequest = contract.MustNew[struct{}]()
|
||||
|
||||
func (h *Handler) Slow(c *httpx.Context) error {
|
||||
if err := slowRequest.BindWithPolicy(c.Request(), httpx.RouteParams(c.Context()), &struct{}{}, contract.RequestPolicy{UnknownQuery: "", UTF8: "", Charset: "", Body: ""}); err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := h.logic.Slow(c.Context())
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -1,39 +0,0 @@
|
||||
package svc
|
||||
|
||||
import "errors"
|
||||
|
||||
// Close is idempotent, including startup failure and graceful shutdown.
|
||||
func (c *ServiceContext) Close() error {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
c.closeOnce.Do(func() {
|
||||
if c.Lifecycle != nil {
|
||||
c.Lifecycle.RequestShutdown(nil)
|
||||
}
|
||||
c.closeMu.Lock()
|
||||
c.closed = true
|
||||
cleanups := c.cleanups
|
||||
c.cleanups = nil
|
||||
c.closeMu.Unlock()
|
||||
for i := len(cleanups) - 1; i >= 0; i-- {
|
||||
c.closeErr = errors.Join(c.closeErr, cleanups[i]())
|
||||
}
|
||||
|
||||
})
|
||||
return c.closeErr
|
||||
}
|
||||
|
||||
// OnClose transfers a resource cleanup to this context immediately after creation.
|
||||
// Hooks run once in reverse order, also when later initialization fails.
|
||||
func (c *ServiceContext) OnClose(cleanup func() error) {
|
||||
if cleanup == nil {
|
||||
return
|
||||
}
|
||||
c.closeMu.Lock()
|
||||
defer c.closeMu.Unlock()
|
||||
if c.closed {
|
||||
panic("svc: register cleanup after Close")
|
||||
}
|
||||
c.cleanups = append(c.cleanups, cleanup)
|
||||
}
|
||||
56
examples/managedService/internal/svc/runtimeGen.go
Normal file
56
examples/managedService/internal/svc/runtimeGen.go
Normal file
@@ -0,0 +1,56 @@
|
||||
// Code generated by go-omni api. DO NOT EDIT.
|
||||
package svc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"git.yuntuo.hk/k2safe/go-omni/health"
|
||||
"git.yuntuo.hk/k2safe/go-omni/lifecycle"
|
||||
"git.yuntuo.hk/k2safe/go-omni/logx"
|
||||
|
||||
"example.com/managed/internal/config"
|
||||
"example.com/managed/internal/middleware"
|
||||
)
|
||||
|
||||
// New is generator-owned. Customize dependencies in ServiceContext.Init.
|
||||
func New(ctx context.Context, logger *logx.Logger, configs ...config.Config) (result *ServiceContext, err error) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
if err = ctx.Err(); err != nil {
|
||||
return nil, errors.Join(err, lifecycle.Cause(ctx))
|
||||
}
|
||||
if logger == nil {
|
||||
return nil, errors.New("service context requires a logger")
|
||||
}
|
||||
if len(configs) > 1 {
|
||||
return nil, errors.New("expected at most one configuration")
|
||||
}
|
||||
cfg := config.Default()
|
||||
if len(configs) == 1 {
|
||||
cfg = configs[0]
|
||||
}
|
||||
if err = cfg.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
checker, err := health.New()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c := &ServiceContext{Config: cfg, Logger: logger, Health: checker, Middlewares: middleware.Defaults(), Runtime: lifecycle.NewRuntime(ctx)}
|
||||
ctx = logx.WithLogger(c.Context(), logger)
|
||||
defer func() {
|
||||
if p := recover(); p != nil {
|
||||
_ = c.Close()
|
||||
panic(p)
|
||||
}
|
||||
if err != nil {
|
||||
err = c.Finish(err)
|
||||
}
|
||||
}()
|
||||
|
||||
if err = c.Init(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
@@ -2,66 +2,25 @@ package svc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
|
||||
"example.com/managed/internal/config"
|
||||
"example.com/managed/internal/middleware"
|
||||
"git.yuntuo.hk/k2safe/go-omni/health"
|
||||
"git.yuntuo.hk/k2safe/go-omni/httpx"
|
||||
"git.yuntuo.hk/k2safe/go-omni/lifecycle"
|
||||
"git.yuntuo.hk/k2safe/go-omni/logx"
|
||||
)
|
||||
|
||||
// Context owns infrastructure, while Logger is borrowed from main.
|
||||
// Add business repositories here; HTTP contracts do not define database tables.
|
||||
// Context holds project dependencies. Runtime owns cleanup and shutdown.
|
||||
// Logger is borrowed; the generated entry closes it after dependencies.
|
||||
type ServiceContext struct {
|
||||
Lifecycle *lifecycle.Controller
|
||||
*lifecycle.Runtime
|
||||
Config config.Config
|
||||
cleanups []func() error
|
||||
Logger *logx.Logger
|
||||
Health *health.Checker
|
||||
Middlewares map[string]httpx.Middleware
|
||||
|
||||
closeMu sync.Mutex
|
||||
closed bool
|
||||
closeOnce sync.Once
|
||||
closeErr error
|
||||
}
|
||||
|
||||
// Pass the settings loaded by main. The optional form supports lightweight
|
||||
// tests without infrastructure; selected adapters still require valid config.
|
||||
func New(ctx context.Context, logger *logx.Logger, configs ...config.Config) (result *ServiceContext, err error) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
if err = ctx.Err(); err != nil {
|
||||
return nil, errors.Join(err, lifecycle.Cause(ctx))
|
||||
}
|
||||
if len(configs) > 1 {
|
||||
return nil, errors.New("expected at most one configuration")
|
||||
}
|
||||
cfg := config.Default()
|
||||
if len(configs) == 1 {
|
||||
cfg = configs[0]
|
||||
}
|
||||
_ = cfg
|
||||
checker, err := health.New()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c := &ServiceContext{Config: cfg, Logger: logger, Health: checker, Middlewares: middleware.Defaults(), Lifecycle: lifecycle.New(ctx)}
|
||||
ctx = c.Lifecycle.Context()
|
||||
defer func() {
|
||||
if err != nil {
|
||||
err = errors.Join(err, c.Close())
|
||||
if cause := c.Lifecycle.Err(); cause != nil && !errors.Is(err, cause) {
|
||||
err = errors.Join(err, cause)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (c *ServiceContext) RequestShutdown(err error) { c.Lifecycle.RequestShutdown(err) }
|
||||
// Init is project-owned. Add dependencies here and immediately register each
|
||||
// cleanup with c.OnClose. Returning an error automatically rolls everything back.
|
||||
// Generated infrastructure is ready here. Never create another App or logger.
|
||||
func (c *ServiceContext) Init(ctx context.Context) error { return nil }
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
// Code generated by go-omni api. DO NOT EDIT.
|
||||
package types
|
||||
|
||||
type CheckReq struct {
|
||||
Kind string `form:"kind,optional"`
|
||||
}
|
||||
type Receipt struct {
|
||||
Bytes int64 `json:"bytes"`
|
||||
}
|
||||
@@ -1,9 +1,2 @@
|
||||
// Code generated by go-omni api. DO NOT EDIT.
|
||||
package types
|
||||
|
||||
type CheckReq struct {
|
||||
Kind string `form:"kind,optional"`
|
||||
}
|
||||
type Receipt struct {
|
||||
Bytes int64 `json:"bytes"`
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user