Skip to content

Commit 29cf144

Browse files
authored
Merge pull request #18 from lvan100/main
optimizes code comments
2 parents e75fa70 + 757c79a commit 29cf144

File tree

21 files changed

+238
-89
lines changed

21 files changed

+238
-89
lines changed

gs/examples/bookman/.cover/cover.html

Lines changed: 104 additions & 43 deletions
Large diffs are not rendered by default.

gs/examples/bookman/README.md

Whitespace-only changes.

gs/examples/bookman/init.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,10 @@ func init() {
3737
gs.Banner(banner)
3838
}
3939

40+
// init sets the working directory of the application to the directory
41+
// where this source file resides.
42+
// This ensures that any relative file operations are based on the source file location,
43+
// not the process launch path.
4044
func init() {
4145
var execDir string
4246
_, filename, _, ok := runtime.Caller(0)

gs/examples/bookman/src/app/bootstrap/bootstrap.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ func initRemoteConfig() error {
3737
if err := getRemoteConfig(); err != nil {
3838
return err
3939
}
40+
// Register a function job to refresh the configuration.
41+
// A bean can be registered into the app during the bootstrap phase.
4042
gs.FuncJob(refreshRemoteConfig)
4143
return nil
4244
}
@@ -74,14 +76,18 @@ func getRemoteConfig() error {
7476
func refreshRemoteConfig(ctx context.Context) error {
7577
for {
7678
select {
77-
case <-ctx.Done():
79+
case <-ctx.Done(): // Gracefully exit when context is canceled.
80+
// The context (ctx) is derived from the app instance.
81+
// When the app exits, the context is canceled,
82+
// allowing the loop to terminate gracefully.
7883
fmt.Println("config updater exit")
7984
return nil
8085
case <-time.After(time.Millisecond * 500):
8186
if err := getRemoteConfig(); err != nil {
8287
fmt.Println("get remote config error:", err)
8388
return err
8489
}
90+
// Refreshes the app configuration.
8591
if err := gs.RefreshProperties(); err != nil {
8692
fmt.Println("refresh properties error:", err)
8793
return err

gs/examples/bookman/src/app/common/handlers/log/log.go

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,29 +26,43 @@ import (
2626
)
2727

2828
func init() {
29+
// Register a group of Bean definitions during application initialization.
30+
// GroupRegister dynamically creates multiple Beans based on the configuration (conf.Properties),
31+
// making it ideal for scenarios like setting up multiple loggers, clients, or resources from config.
2932
gs.GroupRegister(func(p conf.Properties) ([]*gs.BeanDefinition, error) {
33+
3034
var loggers map[string]struct {
31-
Name string `value:"${name}"`
32-
Dir string `value:"${dir}"`
35+
Name string `value:"${name}"` // Log file name
36+
Dir string `value:"${dir}"` // Directory where the log file will be stored
3337
}
38+
39+
// Bind configuration from the "${log}" node into the 'loggers' map.
3440
err := p.Bind(&loggers, "${log}")
3541
if err != nil {
3642
return nil, err
3743
}
44+
3845
var ret []*gs.BeanDefinition
3946
for k, l := range loggers {
4047
var (
4148
f *os.File
4249
flag = os.O_WRONLY | os.O_CREATE | os.O_APPEND
4350
)
51+
52+
// Open (or create) the log file
4453
f, err = os.OpenFile(filepath.Join(l.Dir, l.Name), flag, os.ModePerm)
4554
if err != nil {
4655
return nil, err
4756
}
57+
58+
// Create a new slog.Logger instance with a text handler writing to the file
4859
o := slog.New(slog.NewTextHandler(f, nil))
60+
61+
// Wrap the logger into a Bean with a destroy hook to close the file
4962
b := gs.NewBean(o).Name(k).Destroy(func(_ *slog.Logger) {
5063
_ = f.Close()
5164
})
65+
5266
ret = append(ret, b)
5367
}
5468
return ret, nil

gs/examples/bookman/src/app/common/httpsvr/httpsvr.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,11 +34,13 @@ func init() {
3434
)
3535
}
3636

37-
// NewServeMux Creates a new HTTP request multiplexer and registers
37+
// NewServeMux creates a new HTTP request multiplexer and registers
3838
// routes with access logging middleware.
3939
func NewServeMux(c *controller.Controller, logger *slog.Logger) *http.ServeMux {
4040
mux := http.NewServeMux()
4141
proto.RegisterRouter(mux, c, Access(logger))
42+
43+
// Users can customize routes by adding handlers to the mux
4244
mux.Handle("GET /", http.FileServer(http.Dir("./public")))
4345
return mux
4446
}

gs/examples/bookman/src/app/controller/controller.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,10 @@ func init() {
2424
gs.Object(&Controller{})
2525
}
2626

27+
// Controller implements the controller interface defined in the idl package.
28+
// In practice, controller methods can be grouped into different controllers.
29+
// Each sub-controller can have its own dependencies and be tested independently,
30+
// making the codebase more modular and maintainable.
2731
type Controller struct {
2832
BookController
2933
}

gs/examples/bookman/src/biz/job/job.go

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,11 +34,15 @@ type Job struct{}
3434
func (x *Job) Run(ctx context.Context) error {
3535
for {
3636
select {
37-
case <-ctx.Done(): // Gracefully exit when context is canceled
37+
case <-ctx.Done():
38+
// Gracefully exit when the context is canceled
3839
fmt.Println("job exit")
3940
return nil
4041
default:
41-
if gs.Exiting() { // Check if the system is shutting down
42+
// Check if the app is shutting down.
43+
// In long-running background tasks, checking for shutdown signals
44+
// during idle periods or between stages helps ensure timely resource cleanup.
45+
if gs.Exiting() {
4246
return nil
4347
}
4448
time.Sleep(time.Millisecond * 300)

gs/examples/bookman/src/idl/http/proto/proto.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,14 @@
1414
* limitations under the License.
1515
*/
1616

17+
// Package proto defines the interfaces and route registrations generated from IDL files.
1718
package proto
1819

1920
import (
2021
"net/http"
2122
)
2223

24+
// Book represents the structure of a book entity.
2325
type Book struct {
2426
Title string `json:"title"`
2527
Author string `json:"author"`
@@ -29,13 +31,17 @@ type Book struct {
2931
RefreshTime string `json:"refreshTime"`
3032
}
3133

34+
// Controller defines the service interface for book-related operations.
3235
type Controller interface {
3336
ListBooks(w http.ResponseWriter, r *http.Request)
3437
GetBook(w http.ResponseWriter, r *http.Request)
3538
SaveBook(w http.ResponseWriter, r *http.Request)
3639
DeleteBook(w http.ResponseWriter, r *http.Request)
3740
}
3841

42+
// RegisterRouter registers the HTTP routes for the Controller interface.
43+
// It maps each method to its corresponding HTTP endpoint,
44+
// and applies the given middleware (wrap) to each handler.
3945
func RegisterRouter(mux *http.ServeMux, c Controller, wrap func(next http.Handler) http.Handler) {
4046
mux.Handle("GET /books", wrap(http.HandlerFunc(c.ListBooks)))
4147
mux.Handle("GET /books/{isbn}", wrap(http.HandlerFunc(c.GetBook)))

gs/examples/miniapi/main.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,17 @@ import (
2323
)
2424

2525
func main() {
26+
// Register an HTTP handler for the "/echo" endpoint.
2627
http.HandleFunc("/echo", func(w http.ResponseWriter, r *http.Request) {
2728
_, _ = w.Write([]byte("hello world!"))
2829
})
30+
31+
// Start the Go-Spring framework.
32+
// Compared to http.ListenAndServe, gs.Run() starts a full-featured application context with:
33+
// - Auto Configuration: Automatically loads properties and beans.
34+
// - Property Binding: Binds external configs (YAML, ENV) into structs.
35+
// - Dependency Injection: Wires beans automatically.
36+
// - Dynamic Refresh: Updates configs at runtime without restart.
2937
gs.Run()
3038
}
3139

0 commit comments

Comments
 (0)