Skip to content

Update comments #27

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
May 10, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 102 additions & 0 deletions conf/conf.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,108 @@
* limitations under the License.
*/

/*
Package conf provides a configuration binding framework with hierarchical resolution,
type-safe mapping, and validation capabilities.

# Core Concepts:

The framework enables mapping configuration data from multiple sources into Go structures with:

- Hierarchical property resolution using ${key} syntax
- Type-safe binding with automatic conversions
- Expression-based validation
- Extensible architecture via pluggable components

# Tag Syntax:

Struct tags use the following format:

value:"${key:=default}>>splitter"

Key features:
- Nested keys (e.g., service.endpoint)
- Dynamic defaults (e.g., ${DB_HOST:=localhost:${DB_PORT:=3306}})
- Splitter chaining (e.g., >>json for JSON parsing)

# Data Binding:

Supports binding to various types with automatic conversion:

1. Primitives: Uses strconv for basic type conversions
2. Complex Types:
- Slices: From indexed properties or custom splitters
- Maps: Via subkey expansion
- Structs: Recursive binding of nested structures

3. Custom Types: Register converters using RegisterConverter

# Validation System:

1. Expression validation using expr tag:
type Config struct {
Port int `expr:"$ > 0 && $ < 65535"`
}

2. Custom validators:
RegisterValidateFunc("futureDate", func(t time.Time) bool {
return t.After(time.Now())
})

# File Support:

Built-in readers handle:
- JSON (.json)
- Properties (.properties)
- YAML (.yaml/.yml)
- TOML (.toml/.tml)

Register custom readers with RegisterReader.

# Property Resolution:

- Recursive ${} substitution
- Type-aware defaults
- Chained defaults (${A:=${B:=C}})

# Extension Points:

1. RegisterSplitter: Add custom string splitters
2. RegisterConverter: Add type converters
3. RegisterReader: Support new file formats
4. RegisterValidateFunc: Add custom validators

# Examples:

Basic binding:

type ServerConfig struct {
Host string `value:"${host:=localhost}"`
Port int `value:"${port:=8080}"`
}

Nested structure:

type AppConfig struct {
DB Database `value:"${db}"`
Timeout string `value:"${timeout:=5s}"`
}

Slice binding:

type Config struct {
Endpoints []string `value:"${endpoints}"` // Indexed properties
Features []string `value:"${features}>>split"` // Custom splitter
}

Validation:

type UserConfig struct {
Age int `value:"${age}" expr:"$ >= 18"`
Email string `value:"${email}" expr:"contains($, '@')"`
Expires time.Time `value:"${expires}" expr:"futureDate($)"`
}
*/
package conf

import (
Expand Down
40 changes: 35 additions & 5 deletions gs/gstest/gstest.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,41 @@
* limitations under the License.
*/

// Package gstest is a unit testing framework designed for dependency injection in go-spring.
// Unlike standard dependency injection, in unit testing mode, the framework gracefully ignores
// non-critical dependency injection failures by logging warnings instead of halting execution.
// This ensures seamless testing workflows when dealing with extensive dependencies,
// as only the specific dependencies under test need to be validated, while others remain non-blocking.
/*
Package gstest provides unit testing utilities for dependency injection in Go-Spring framework.

Key Features:
- Test environment configuration: jobs and servers are disabled, and the "test" profile is automatically activated
- Autowire failure tolerance: non-critical autowiring errors are tolerated so that missing beans do not break tests
- Type-safe mocking: compile-time checked MockFor/With methods for registering mock beans
- Context lifecycle management: TestMain starts and stops the Go-Spring context automatically
- Injection helpers: Get[T](t) and Wire(t, obj) simplify bean retrieval and dependency injection

Usage Pattern:

// Step 1: Register your mock beans before tests run
// by calling `MockFor[T]().With(obj)` inside an `init()` function.
func init() {
gstest.MockFor[*Dao]().With(&MockDao{})
}

// Step 2: Implement TestMain and invoke `gstest.TestMain(m, opts...)`
// to bootstrap the application context, execute all tests, and then shut it down.
// You can supply `BeforeRun` and `AfterRun` hooks to run code immediately before or after your test suite.
func TestMain(m *testing.M) {
gstest.TestMain(m)
}

// Step 3: Write your test cases and use Get[T](t) or Wire(t, obj) to retrieve beans and inject dependencies.
func TestService(t *testing.T) {
// Retrieve autowired test target
service := gstest.Get[*Service](t)

// Verify business logic
result := service.Process()
assert.Equal(t, expect, result)
}
*/
package gstest

import (
Expand Down
10 changes: 10 additions & 0 deletions gs/internal/gs_arg/arg.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,16 @@
* limitations under the License.
*/

/*
Package gs_arg provides implementation for function argument resolution and binding

Key Features:
- Configuration property binding and dependency injection via struct tags
- Precise positional binding through index-based arguments
- Direct injection of fixed value arguments
- Full support for variadic function parameters
- Conditional execution with runtime evaluation
*/
package gs_arg

import (
Expand Down
9 changes: 9 additions & 0 deletions gs/internal/gs_bean/bean.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,15 @@
* limitations under the License.
*/

/*
Package gs_bean provides core bean management for Go-Spring framework, featuring:

- Full lifecycle management (instantiation, DI, destruction)
- Method-as-factory mechanism (generate child beans via configured rules)
- Conditional registration (profile-based activation)
- Type-safe interface export validation
- Mock replacement mechanism
*/
package gs_bean

import (
Expand Down
53 changes: 53 additions & 0 deletions gs/internal/gs_cond/cond.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,59 @@
* limitations under the License.
*/

/*
Package gs_cond provides conditional component registration for Go-Spring framework,
offering runtime decision-making through various condition types.

1. Property Conditions

- Existence check:
cond := OnProperty("db.host")

- Value matching:
cond := OnProperty("env").HavingValue("prod")

- Expression evaluation:
cond := OnProperty("port").HavingValue("expr:int($) > 1024")

- Missing handling:
cond := OnProperty("debug").MatchIfMissing()

2. Bean Conditions

- Existence verification:
cond := OnBean[Database]()

- Absence check:
cond := OnMissingBean[Logger]()

- Singleton validation:
cond := OnSingleBean[Config]()

3. Logical Combinators

- Conjunction:
cond := And(condition1, condition2)

- Disjunction:
cond := Or(condition1, condition2)

- Negation:
cond := Not(condition)

- Universal negation:
cond := None(condition1, condition2)

4. Custom Conditions

- Functional condition:
cond := OnFunc(func(ctx gs.CondContext) (bool, error) {
return time.Now().Hour() > 9, nil
})

- Expression condition (Pending implementation):
cond := OnExpression("beans('redis').size() > 0")
*/
package gs_cond

import (
Expand Down
27 changes: 27 additions & 0 deletions gs/internal/gs_conf/conf.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,33 @@
* limitations under the License.
*/

/*
Package gs_conf provides hierarchical configuration management
with multi-source support for Go-Spring framework.

Key Features:

1. Command-line argument parsing
- Supports `-D key[=value]` format arguments
- Customizable prefix via `GS_ARGS_PREFIX` environment variable
- Example: `./app -D server.port=8080 -D debug`

2. Environment variable handling
- Automatic loading of `GS_` prefixed variables
- Conversion rules: `GS_DB_HOST=127.0.0.1` → `db.host=127.0.0.1`
- Direct mapping of non-prefixed environment variables

3. Configuration file management
- Supports properties/yaml/toml/json formats
- Local configurations: ./conf/app.{properties|yaml|toml|json}
- Remote configurations: ./conf/remote/app.{properties|yaml|toml|json}
- Profile-based configurations (e.g., app-dev.properties)

4. Layered configuration hierarchy
- Priority order: System config → File config → Env variables → CLI arguments
- Provides AppConfig (application context) and BootConfig (boot context)
- High-priority configurations override lower ones
*/
package gs_conf

import (
Expand Down
3 changes: 3 additions & 0 deletions gs/internal/gs_conf/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@
if len(ss) > 1 {
v = ss[1]
}
if k == "" { // e.g., =::=::
continue

Check warning on line 49 in gs/internal/gs_conf/env.go

View check run for this annotation

Codecov / codecov/patch

gs/internal/gs_conf/env.go#L49

Added line #L49 was not covered by tests
}
var propKey string
if strings.HasPrefix(k, prefix) {
propKey = strings.TrimPrefix(k, prefix)
Expand Down
44 changes: 44 additions & 0 deletions gs/internal/gs_dync/dync.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,50 @@
* limitations under the License.
*/

/*
Package gs_dync provides dynamic configuration binding and refresh capabilities for Go applications.

This package is built on thread-safe atomic.Value storage with automatic type conversion and supports change listeners,
making it suitable for components or services that need to react to configuration updates at runtime.

Key Features:
- Type-safe and thread-safe encapsulation of configuration values
- Change notification mechanism using channels
- Hierarchical key resolution for nested structs and map keys
- Fine-grained refresh logic that only updates affected objects
- JSON serialization support for value persistence and transmission

Examples:

Basic value binding:

var v Value[int]
_ = v.onRefresh(conf.Map(map[string]any{"key": 42}), conf.BindParam{Key: "key"})
fmt.Print(v.Value()) // Output: 42

Binding nested structs:

type Config struct {
Server struct {
Port Value[int] `value:"${port}"`
} `value:"${server}"`
}

var cfg Config
_ = p.RefreshField(reflect.ValueOf(&cfg), conf.BindParam{Key: "config"})

Change notification:

listener := v.NewListener()
go func() {
<-listener.C
fmt.Print("value changed!")
}()
_ = v.onRefresh(conf.Map(map[string]any{"key": 100}), conf.BindParam{Key: "key"})

This package is ideal for use cases that require hot-reloading of configuration, have complex config structures,
or demand reactive behavior to configuration changes.
*/
package gs_dync

import (
Expand Down
Empty file added sdk/mcp/.keep
Empty file.
Loading