### Basic HttpRouter Setup and Routing in Go Source: https://github.com/snail007/gmc/blob/master/http/router/README_BASE.md Demonstrates the basic setup of an HttpRouter in Go, including defining handlers for different routes and starting the HTTP server. It shows how to register GET requests for the root path and a path with a parameter. ```Go package main import ( "fmt" "net/http" "log" "github.com/julienschmidt/httprouter" ) func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { fmt.Fprint(w, "Welcome!\n") } func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name")) } func main() { router := httprouter.New() router.GET("/", Index) router.GET("/hello/:name", Hello) log.Fatal(http.ListenAndServe(":8080", router)) } ``` -------------------------------- ### GMCT Development Workflow Example (Bash) Source: https://github.com/snail007/gmc/blob/master/README_EN.md A step-by-step guide demonstrating a complete development workflow using GMCT. This includes installation, project creation, hot compilation development, resource packaging for production, building the application, and deployment. ```bash # 1. Install GMCT go install github.com/snail007/gmct@latest # 2. Create new project mkdir mywebapp && cd mywebapp gmct new web --pkg github.com/me/mywebapp # 3. Hot compilation development gmct run # Auto recompile and restart after code changes # 4. Pack resources (production) gmct static --dir ./static gmct tpl --dir ./views gmct i18n --dir ./i18n # 5. Build for release go build -ldflags "-s -w" -o myapp # 6. Deploy ./myapp # Single binary file with all resources included ``` -------------------------------- ### Quick Start Examples Source: https://github.com/snail007/gmc/blob/master/util/rate/README.md Example code snippets demonstrating how to use the Sliding Window Limiter and Token Bucket Limiter. ```APIDOC ## Quick Start Examples ### Sliding Window Limiter Example ```go package main import ( "fmt" "time" "github.com/snail007/gmc/util/rate" ) func main() { // Create a limiter: max 10 requests per second limiter := grate.NewSlidingWindowLimiter(10, time.Second) for i := 0; i < 20; i++ { if limiter.Allow() { fmt.Printf("Request %d allowed\n", i) } else { fmt.Printf("Request %d rejected\n", i) } time.Sleep(50 * time.Millisecond) } } ``` ### Token Bucket Limiter Example ```go package main import ( "fmt" "time" "github.com/snail007/gmc/util/rate" ) func main() { // Create a limiter: 10 tokens per second, burst capacity 10 limiter := grate.NewTokenBucketLimiter(10, time.Second) // Create a limiter with custom burst capacity: 10 tokens per second, burst capacity 20 burstLimiter := grate.NewTokenBucketBurstLimiter(10, time.Second, 20) for i := 0; i < 15; i++ { if limiter.Allow() { fmt.Printf("Request %d allowed\n", i) } else { fmt.Printf("Request %d rejected\n", i) } } } ``` ### API Handler Rate Limiting Example (Sliding Window) ```go package main import ( "net/http" "time" "github.com/snail007/gmc/util/rate" ) var limiter = grate.NewSlidingWindowLimiter(100, time.Second) func apiHandler(w http.ResponseWriter, r *http.Request) { if !limiter.Allow() { http.Error(w, "Rate limit exceeded", http.StatusTooManyRequests) return } // Handle normal request w.Write([]byte("OK")) } ``` ``` -------------------------------- ### Install glist Package Source: https://github.com/snail007/gmc/blob/master/util/list/README.md This command installs the glist package from the specified GitHub repository using the go get command. Ensure you have Go installed and configured. ```bash go get github.com/snail007/gmc/util/list ``` -------------------------------- ### Development Workflow Example Source: https://github.com/snail007/gmc/blob/master/README_EN.md A step-by-step example demonstrating a complete development workflow using GMCT, from installation to deployment. ```APIDOC ## 🎬 Complete Development Workflow Example ```bash # 1. Install GMCT go install github.com/snail007/gmct@latest # 2. Create new project mkdir mywebapp && cd mywebapp gmct new web --pkg github.com/me/mywebapp # 3. Hot compilation development gmct run # Auto recompile and restart after code changes # 4. Pack resources (production) gmct static --dir ./static gmct tpl --dir ./views gmct i18n --dir ./i18n # 5. Build for release go build -ldflags "-s -w" -o myapp # 6. Deploy ./myapp # Single binary file with all resources included ``` ``` -------------------------------- ### Quick Start with glist List Source: https://github.com/snail007/gmc/blob/master/util/list/README.md Demonstrates the basic usage of the glist package for creating a thread-safe list, adding elements, retrieving, setting, removing, and iterating over them. It also shows how to get the length of the list. ```go package main import ( "fmt" "github.com/snail007/gmc/util/list" ) func main() { list := glist.New() // 添加元素 list.Add("apple", "banana", "cherry") // 获取元素 fmt.Println(list.Get(0)) // apple // 设置元素 list.Set(1, "blueberry") // 删除元素 list.Remove(2) // 遍历 list.Range(func(index int, value interface{}) bool { fmt.Printf("%d: %v\n", index, value) return true }) // 长度 fmt.Println("Length:", list.Len()) } ``` -------------------------------- ### Usage Scenarios Source: https://github.com/snail007/gmc/blob/master/util/env/README.md Examples demonstrating practical applications of the genv package, such as application configuration and multi-environment setups. ```APIDOC ## Usage Scenarios ### Application Configuration Management This scenario demonstrates how to load application configuration from environment variables using the genv package. ```go package main import ( "fmt" "github.com/snail007/gmc/util/env" ) type Config struct { Host string Port int Debug bool Timeout int } func LoadConfig() *Config { envAccessor := genv.NewAccessor("MYAPP_") return &Config{ Host: envAccessor.Get("HOST").String(), Port: envAccessor.Get("PORT").Int(), Debug: envAccessor.Get("DEBUG").Bool(), Timeout: envAccessor.Get("TIMEOUT").Int(), } } func main() { // Example of setting environment variables for testing env := genv.NewAccessor("MYAPP_") env.Set("HOST", "localhost"). Set("PORT", "8080"). Set("DEBUG", "true"). Set("TIMEOUT", "30") config := LoadConfig() fmt.Printf("%+v\n", config) } ``` ### Multi-Environment Configuration This example illustrates how to manage configurations for different environments (e.g., development, production) using distinct prefixes with genv. ```go package main import ( "github.com/snail007/gmc/util/env" ) func main() { // Development environment configuration devEnv := genv.NewAccessor("DEV_") devEnv.Set("DB_HOST", "localhost"). Set("DB_PORT", "5432") // Production environment configuration prodEnv := genv.NewAccessor("PROD_") prodEnv.Set("DB_HOST", "prod-db.example.com"). Set("DB_PORT", "5432") // Example: Select configuration based on an environment variable or flag var currentEnv *genv.Accessor // In a real application, you would determine currentEnv dynamically currentEnv = prodEnv // Assuming production environment dbHost := currentEnv.Get("DB_HOST").String() println("Database Host:", dbHost) } ``` ``` -------------------------------- ### Install GMC Database Module Source: https://github.com/snail007/gmc/blob/master/module/db/README.md Instructions for installing the GMC Database module using go get. This command fetches and installs the specified package and its dependencies. ```bash go get github.com/snail007/gmc/module/db ``` -------------------------------- ### Go: Making GET and POST Requests Source: https://github.com/snail007/gmc/blob/master/util/http/README.md Provides examples of making basic GET and POST requests using the ghttp library. It shows how to specify the URL, timeout, query parameters for GET, and form data for POST. Error handling is implicitly shown through return values. ```go // GET 请求 users, _, _, _ := ghttp.Get("https://api.example.com/users", 5*time.Second, nil, nil) // POST 创建资源 body, code, _, err := ghttp.Post( "https://api.example.com/users", map[string]string{"name": "张三"}, 5*time.Second, nil, ) ``` -------------------------------- ### Controller Setup with GMCT (Go) Source: https://github.com/snail007/gmc/blob/master/README_EN.md Illustrates how to define and register controllers in GMCT for handling specific routes. It shows a basic controller structure with methods for listing users and getting user details, and how to associate them with a router. ```go type UserController struct { gmc.Controller } func (c *UserController) List() { users := []string{"Alice", "Bob", "Charlie"} c.Write(users) } func (c *UserController) Detail() { id := c.Param().ByName("id") c.Write("User ID: " + id) } // Register in router router.Controller("/user", new(UserController)) ``` -------------------------------- ### Install GMC Controller Package Source: https://github.com/snail007/gmc/blob/master/http/controller/README.md Command to install the GMC controller package using go get. ```bash go get github.com/snail007/gmc ``` -------------------------------- ### Start a Daemon Process in Go Source: https://github.com/snail007/gmc/blob/master/util/exec/README.md This example shows how to start a daemon process using gmc/util/exec. It constructs a command to navigate to an application directory and run a background process, redirecting its output to a log file. The `Detach(true)` option is used to ensure the process runs independently. ```go package main import ( "github.com/snail007/gmc/util/exec" ) func startDaemon() error { cmd := gexec.NewCommand(` cd /app nohup ./myapp > /var/log/myapp.log 2>&1 & `) cmd.Detach(true) _, err := cmd.Exec() return err } ``` -------------------------------- ### Install gmc/util/map Package Source: https://github.com/snail007/gmc/blob/master/util/map/README.md This command installs the gmc/util/map package using the Go get command. Ensure you have Go installed and configured correctly. ```bash go get github.com/snail007/gmc/util/map ``` -------------------------------- ### Install gcompress Library Source: https://github.com/snail007/gmc/blob/master/util/compress/README.md This command installs the gcompress utility library from the GMC framework using go get. It's the primary method for adding this functionality to your Go project. ```bash go get github.com/snail007/gmc/util/compress ``` -------------------------------- ### Install GMC AccessLog Middleware Source: https://github.com/snail007/gmc/blob/master/module/middleware/accesslog/README.md Command to install the GMC AccessLog middleware using go get. ```bash go get github.com/snail007/gmc/module/middleware/accesslog ``` -------------------------------- ### Install gset Package Source: https://github.com/snail007/gmc/blob/master/util/set/README.md This command installs the gset package, which provides a thread-safe set implementation. Ensure you have Go installed and configured correctly. ```bash go get github.com/snail007/gmc/util/set ``` -------------------------------- ### Web Server Task Handling with Optimized gpool (Go) Source: https://github.com/snail007/gmc/blob/master/util/gpool/MIGRATION_GUIDE.md Shows a practical example of using the optimized gpool in a web server to handle incoming requests asynchronously. A global task pool is created to manage background processing, improving responsiveness. This snippet requires the `net/http` package and the gmc gpool library. ```go // 创建全局pool var taskPool = gpool.NewOptimized(1000) func handleRequest(w http.ResponseWriter, r *http.Request) { // 异步处理任务 taskPool.Submit(func() { // 处理耗时操作 processData() }) w.Write([]byte("Processing...")) } ``` -------------------------------- ### GMCT Toolchain: Install from Source Source: https://github.com/snail007/gmc/blob/master/docs/zh/MANUAL_ZH.md This bash script demonstrates how to install the GMCT toolchain from its source code. It involves cloning the repository, navigating into the directory, and then using `go install` to compile and install the executable. Finally, it shows how to verify the installation by checking the version. ```bash # 克隆仓库 git clone https://github.com/snail007/gmct.git cd gmct # 编译安装 go install # 验证安装 gmct version ``` -------------------------------- ### Install gexec Package Source: https://github.com/snail007/gmc/blob/master/util/exec/README.md Command to install the gexec utility from the specified Go module path. ```bash go get github.com/snail007/gmc/util/exec ``` -------------------------------- ### GMCT Toolchain: Install using go install Source: https://github.com/snail007/gmc/blob/master/docs/zh/MANUAL_ZH.md This command demonstrates installing the GMCT toolchain directly using `go install`. It specifies the latest version of the `gmct` command from the specified repository. After installation, it shows how to verify the installation by checking the version. ```bash go install github.com/snail007/gmct/cmd/gmct@latest gmct version ``` -------------------------------- ### Microservice Calls with Optimized gpool and Panic Handling (Go) Source: https://github.com/snail007/gmc/blob/master/util/gpool/MIGRATION_GUIDE.md Demonstrates concurrent calls to multiple microservices using the optimized gpool, including custom panic handling for each service call. This example utilizes `NewOptimizedWithOption` to configure a `PanicHandler`, ensuring that panics in individual service calls do not bring down the entire application. Requires the gmc gpool library and standard Go concurrency primitives like `sync.Mutex`. ```go func callMultipleServices() ([]Response, error) { p := gpool.NewOptimizedWithOption(10, &gpool.Option{ PanicHandler: func(e interface{}) { log.Printf("Service call panic: %v", e) }, }) defer p.Stop() results := make([]Response, len(services)) var mu sync.Mutex for i, svc := range services { i, svc := i, svc p.Submit(func() { resp, err := svc.Call() mu.Lock() results[i] = resp mu.Unlock() }) } p.WaitDone() return results, nil } ``` -------------------------------- ### GMC Application Lifecycle Hooks in Go Source: https://github.com/snail007/gmc/blob/master/docs/zh/MANUAL_ZH.md Illustrates the setup and usage of lifecycle hooks within a GMC application. It shows how to create a new application instance, set a configuration file, define actions for pre-start (`OnRun`) and shutdown (`OnShutdown`) phases, and finally start the application. ```go // 创建应用 app := gmc.New.App() // 设置配置文件 app.SetConfigFile("conf/app.toml") // OnRun 钩子:在服务启动前执行 app.OnRun(func(cfg gcore.Config) error { // 初始化数据库连接 // 注册路由 // 其他初始化操作 return nil }) // OnShutdown 钩子:在服务停止时执行 app.OnShutdown(func() { // 关闭数据库连接 // 清理资源 fmt.Println("应用正在关闭...") }) // 启动应用 app.Run() ``` -------------------------------- ### Go File Download Examples Source: https://github.com/snail007/gmc/blob/master/docs/zh/MANUAL_ZH.md Provides examples for handling file downloads in Go controllers. It covers direct file output, specifying a download filename, and serving files from a custom file system. ```go func (this *User) Download() { // 直接输出文件 this.Ctx.WriteFile("/path/to/file.pdf") // 指定下载文件名 this.Ctx.WriteFileAttachment("/path/to/file.pdf", "report.pdf") // 从自定义文件系统读取 fs := http.Dir("uploads") this.Ctx.WriteFileFromFS("document.pdf", fs) } ``` -------------------------------- ### Basic Usage of gset Package in Go Source: https://github.com/snail007/gmc/blob/master/util/set/README.md Demonstrates the fundamental operations of the gset package, including creating a new set, adding elements (with automatic deduplication), checking for element existence, getting the set's size, iterating through elements, removing elements, and converting the set to a slice. This example highlights the thread-safe nature and ease of use for managing unique items. ```go package main import ( "fmt" "github.com/snail007/gmc/util/set" ) func main() { set := gset.New() // 添加元素 set.Add("apple") set.Add("banana") set.Add("apple") // 重复元素不会添加 // 检查是否存在 if set.Has("apple") { fmt.Println("Set contains apple") } // 获取大小 fmt.Println("Size:", set.Len()) // 遍历 set.Range(func(item interface{}) bool { fmt.Println(item) return true }) // 删除 set.Remove("banana") // 转换为切片 items := set.Items() fmt.Println(items) } ``` -------------------------------- ### Install GMCT Tool with GOPROXY Configuration Source: https://github.com/snail007/gmc/blob/master/docs/zh/MANUAL_ZH.md This Bash script shows how to install the GMCT tool, ensuring proper configuration for Go modules. It emphasizes setting the GOPROXY environment variable, which is crucial for reliable package retrieval, and then proceeds with the installation using `go install`. ```bash export GOPROXY=https://goproxy.cn,direct go install github.com/snail007/gmct/cmd/gmct@latest ``` -------------------------------- ### genv Package Overview Source: https://github.com/snail007/gmc/blob/master/util/env/README.md Introduction to the genv package, its features, and installation instructions. ```APIDOC ## genv Package ### Description The genv package provides a convenient environment variable accessor with automatic prefixing and support for various data type conversions. It allows for fluent, chainable setting of environment variables and checking for their existence. ### Features * **Prefix Support**: Automatically adds a prefix to environment variables. * **Type Conversion**: Returns `gvalue.AnyValue`, supporting multiple type conversions. * **Chained Calls**: Supports chaining calls for setting environment variables. * **Lookup Functionality**: Supports checking if environment variables exist. ### Installation ```bash go get github.com/snail007/gmc/util/env ``` ``` -------------------------------- ### Create and Run a GMC API Service in Go Source: https://github.com/snail007/gmc/blob/master/docs/MANUAL.md This Go code illustrates the setup of a GMC API service. It involves creating an application instance, parsing a configuration file, initializing an API server with context, setting up dependencies like database and cache, registering handlers, adding the API service to the application, and finally running the application. Error handling is included for critical steps. ```go package main import ( "fmt" "github.com/snail007/gmc" gcore "github.com/snail007/gmc/core" "mygmcapi/handlers" ) func main() { // 1. create app app := gmc.New.App() // 2. parse config file cfg, err := gmc.New.ConfigFile("conf/app.toml") if err != nil { app.Logger().Panic(err) } // 3. create api server ctx := gmc.New.Ctx() ctx.SetConfig(cfg) api, err := gmc.New.APIServerDefault(ctx) if err != nil { app.Logger().Panic(err) } //4. init db, cache, handlers // int db gmc.DB.Init(cfg) // init cache gmc.Cache.Init(cfg) // init api handlers handlers.Init(api) // 5. add service app.AddService(gcore.ServiceItem{ Service: api.(gcore.Service), }) // 6. run app if e := gmc.Err.Stack(app.Run()); e != "" { fmt.Println(e) } } ``` -------------------------------- ### Install GMCT via go get (Windows CMD) Source: https://github.com/snail007/gmc/blob/master/docs/MANUAL.md Installs the GMCT tool chain on Windows using `go get`, downloading and installing the specified package. Requires Git and Go 1.12+. ```shell set GO111MODULE=on go get -v github.com/snail007/gmct/cmd/gmct gmct --help ``` -------------------------------- ### GMCT Configuration File Example (TOML) Source: https://github.com/snail007/gmc/blob/master/README_EN.md An example TOML configuration file for GMCT's run command. It shows settings for watching file extensions, excluding directories, defining build and run commands, and specifying restart delays. ```toml [run] # Watch file extensions watch_ext = [ ".go", ".toml", ".html", ".js", ".css" ] # Exclude directories exclude_dir = [ "vendor", ".git", ".idea", "tmp", "bin", ] # Commands before build before_build = [] # Build command build_cmd = "go build -o tmp/app" # Run command run_cmd = "./tmp/app" # Commands after run after_run = [] # Restart delay (milliseconds) restart_delay = 1000 ``` -------------------------------- ### Create Simple Web Server in Go Source: https://github.com/snail007/gmc/blob/master/http/server/README.md Demonstrates how to create a basic HTTP server using GMC. It involves initializing the application, configuring settings, defining a simple route, and running the server. Dependencies include the 'github.com/snail007/gmc' package. ```go package main import ( "github.com/snail007/gmc" ) func main() { // 创建应用 app := gmc.New.App() // 加载配置 cfg := app.Config() cfg.SetConfigFile("app.toml") cfg.ReadInConfig() // 创建 HTTP 服务器 s := gmc.New.HTTPServer(app.Ctx()) s.Init(cfg) // 配置路由 s.Router().HandlerFunc("GET", "/", func(c gmc.C) { c.Write("Hello GMC!") }) // 添加服务到应用 app.AddService(gmc.ServiceItem{ Service: s, }) // 运行应用 app.Run() } ``` -------------------------------- ### Install GMC Cache Module using Go Get Source: https://github.com/snail007/gmc/blob/master/module/cache/README.md This command installs the GMC Cache module using the Go get command. It is the primary method for adding the cache functionality to your Go project. ```bash go get github.com/snail007/gmc/module/cache ``` -------------------------------- ### Basic Routing with GMC HTTP Router Source: https://github.com/snail007/gmc/blob/master/http/router/README.md Demonstrates how to set up basic GET routes for the root path and a '/hello' endpoint using GMC's HTTP server and router. It initializes the application, creates an HTTP server, retrieves the router, defines handlers using HandlerFunc, and runs the application. ```go package main import ( "github.com/snail007/gmc" ) func main() { app := gmc.New.App() s := gmc.New.HTTPServer(app.Ctx()) // 获取路由器 r := s.Router() // 基本路由 r.HandlerFunc("GET", "/", func(c gmc.C) { c.Write("Welcome!") }) r.HandlerFunc("GET", "/hello", func(c gmc.C) { c.Write("Hello, GMC!") }) app.AddService(gmc.ServiceItem{Service: s}) app.Run() } ``` -------------------------------- ### Go Migration Example: Using gpool.Pool Interface Source: https://github.com/snail007/gmc/blob/master/util/gpool/INTERFACE_DESIGN.md Provides an example of how to migrate existing code that might be using a specific pool implementation (like *gpool.Pool) to use the gpool.Pool interface instead. This is the recommended approach for flexibility. ```go import "github.com/snail007/gmc/util/gpool" // 修改前: // var pool *gpool.Pool // pool = gpool.New(10) // 修改后: // 方案1:使用接口(推荐) var pool gpool.Pool pool = gpool.New(10) // 方案2:使用具体类型 // var pool *gpool.BasicPool // pool = gpool.New(10) ``` -------------------------------- ### Original gpool Usage (Go) Source: https://github.com/snail007/gmc/blob/master/util/gpool/MIGRATION_GUIDE.md Demonstrates the basic usage of the original gpool, including creating a pool, submitting tasks, and waiting for completion. No external dependencies are required beyond the gmc library itself. ```go import "github.com/snail007/gmc/util/gpool" // 创建pool p := gpool.New(100) deffer p.Stop() // 提交任务 p.Submit(func() { // 你的任务代码 }) // 等待完成 p.WaitDone() ``` -------------------------------- ### Go Get Form Data Examples Source: https://github.com/snail007/gmc/blob/master/docs/zh/MANUAL_ZH.md Demonstrates how to retrieve form data (GET and POST parameters) and query parameters in Go controllers. It shows how to get specific parameters with default values and how to retrieve all POST or GET data. ```go func (this *User) HandleForm() { // GET 参数 search := this.Ctx.GET("q") page := this.Ctx.GET("page", "1") // POST 数据 username := this.Ctx.POST("username") password := this.Ctx.POST("password") // 优先 POST,其次 GET token := this.Ctx.GetPost("token") // 获取所有表单数据 postData := this.Ctx.POSTData() // map[string]string getData := this.Ctx.GETData() // map[string]string } ``` -------------------------------- ### Install GMC Error Module Source: https://github.com/snail007/gmc/blob/master/module/error/README.md Instructions on how to install the GMC Error module using go get. ```bash go get github.com/snail007/gmc/module/error ``` -------------------------------- ### Go: Create and Run a Simple API Server with GMC Source: https://github.com/snail007/gmc/blob/master/docs/MANUAL.md This snippet demonstrates how to create a simple API server using GMC, register a root endpoint that returns JSON, and run the server. It shows basic API setup without using the full App service management. ```go package main import( "github.com/snail007/gmc" gmap "github.com/snail007/gmc/util/map" ) func main() { api := gmc.New.APIServer(":7082") api.API("/", func(c gmc.C) { c.Write(gmap.M{ "code":0, "message":"Hello GMC!", "data":nil, }) }) app := gmc.New.App() app.AddService(gcore.ServiceItem{ Service: api, BeforeInit: func(s gcore.Service, cfg *gconfig.Config)(err error) { api.PrintRouteTable(nil) return }, }) if e := gerror.Stack(app.Run());e!=""{ app.Logger().Panic(e) } } ``` ```go package main import( "github.com/snail007/gmc" ) func main() { api,_:= gmc.New.APIServer(gmc.New.Ctx(),":7082") api.Ext(".json") api.API("/hello", func(c gmc.C) { c.Write(gmap.M{ "code":0, "message":"Hello GMC!", "data":nil, }) }) if e := gmc.Err.Stack(api.Run());e!=""{ panic(e) } } ``` -------------------------------- ### Optimized gpool Usage (Go) Source: https://github.com/snail007/gmc/blob/master/util/gpool/MIGRATION_GUIDE.md Shows how to use the optimized gpool, highlighting the change in pool creation. The rest of the API remains identical to the original version, ensuring easy migration. Dependencies are the same as the original gpool. ```go import "github.com/snail007/gmc/util/gpool" // 只需改变创建方式 p := gpool.NewOptimized(100) // 就这里不同! deffer p.Stop() // 其他代码完全相同 p.Submit(func() { // 你的任务代码 }) p.WaitDone() ``` -------------------------------- ### Install glinklist package Source: https://github.com/snail007/gmc/blob/master/util/linklist/README.md Installs the glinklist package from the specified Go module path. This command is used to fetch and manage external Go dependencies. ```bash go get github.com/snail007/gmc/util/linklist ``` -------------------------------- ### Install GMC App Module Source: https://github.com/snail007/gmc/blob/master/module/app/README.md This command installs the GMC App module using the Go get command. It is a prerequisite for using the module in your Go projects. ```bash go get github.com/snail007/gmc/module/app ``` -------------------------------- ### Execute Basic Command in Go Source: https://github.com/snail007/gmc/blob/master/util/exec/README.md Demonstrates how to execute a simple shell command ('echo Hello, World!') using the gexec package and capture its output. ```go package main import ( "fmt" "github.com/snail007/gmc/util/exec" ) func main() { cmd := gexec.NewCommand("echo 'Hello, World!'") output, err := cmd.Exec() if err != nil { panic(err) } fmt.Println(output) } ``` -------------------------------- ### Accessing GET Parameters in GMC Templates Source: https://github.com/snail007/gmc/blob/master/http/view/README.md Example of accessing GET request parameters within GMC templates using the `.G` variable. Demonstrates how to retrieve query string values. ```html

关键词: {{.G.keyword}}

页码: {{.G.page}}

``` -------------------------------- ### Use Default Configuration Values (Go) Source: https://github.com/snail007/gmc/blob/master/module/config/README.md Demonstrates setting up configuration by specifying search paths, configuration file name, and type, then reading the configuration. It also shows how to retrieve a configuration value, like the server port, which might be read from a file or use defaults if not found. ```go package main import ( "github.com/snail007/gmc/module/config" ) func main() { cfg := gconfig.New() // 设置配置搜索路径 cfg.AddConfigPath(".") cfg.AddConfigPath("./conf") cfg.AddConfigPath("./config") // 设置配置文件名(不含扩展名) cfg.SetConfigName("app") // 设置配置文件类型 cfg.SetConfigType("toml") // 读取配置 err := cfg.ReadInConfig() if err != nil { panic(err) } // 使用配置 port := cfg.GetInt("server.port") } ``` -------------------------------- ### Go: WaitFirstSuccess with resource cleanup for primary/backup sources Source: https://github.com/snail007/gmc/blob/master/util/batch/README.md This example shows how to use WaitFirstSuccess to fetch data from primary and backup sources. It includes context-aware cleanup logic, where pending requests are cancelled if a source task is not the first to successfully return data. ```go executor := gbatch.NewBatchExecutor() // 任务 1:尝试从主数据源获取executor.AppendTask(func(ctx context.Context) (interface{}, error) { conn := openConnection("primary") defer func() { // 总是关闭连接 conn.Close() }() // 后台监听取消,执行额外清理 go func() { <-ctx.Done() if !gbatch.IsFirstSuccess(ctx) { // 不是第一个成功的,执行清理 log.Println("Primary source cancelled, cleaning up...") cancelPendingRequests(conn) } }() return fetchFromPrimary(ctx, conn) }) // 任务 2:尝试从备份数据源获取executor.AppendTask(func(ctx context.Context) (interface{}, error) { conn := openConnection("backup") defer conn.Close() go func() { <-ctx.Done() if !gbatch.IsFirstSuccess(ctx) { log.Println("Backup source cancelled, cleaning up...") cancelPendingRequests(conn) } }() return fetchFromBackup(ctx, conn) }) // 使用第一个成功的结果 data, err := executor.WaitFirstSuccess() if err != nil { log.Fatal("All sources failed:", err) } fmt.Println("Got data:", data) ``` -------------------------------- ### Basic usage of glinklist package Source: https://github.com/snail007/gmc/blob/master/util/linklist/README.md Demonstrates the basic usage of the glinklist package, including creating a new list, appending elements, iterating through the list, and getting its length. Assumes the glinklist package has been installed. ```go package main import ( "fmt" "github.com/snail007/gmc/util/linklist" ) func main() { list := glinklist.New() // 添加元素 list.Append(1) list.Append(2) list.Append(3) // 遍历 list.Range(func(v interface{}) bool { fmt.Println(v) return true }) // 获取长度 fmt.Println("Length:", list.Len()) } ``` -------------------------------- ### Example: Handling Configuration Values Source: https://github.com/snail007/gmc/blob/master/util/value/README.md Demonstrates how to use gvalue to safely parse configuration settings. ```APIDOC ## Example: Handling Configuration Values ```go package main import ( "fmt" "github.com/snail007/gmc/util/value" ) func main() { config := map[string]interface{}{ "port": "8080", "debug": "true", "timeout": 30, } port := gvalue.New(config["port"]).Int() debug := gvalue.New(config["debug"]).Bool() timeout := gvalue.New(config["timeout"]).Int() fmt.Printf("Port: %d, Debug: %v, Timeout: %d\n", port, debug, timeout) } ``` ``` -------------------------------- ### API Routing Source: https://github.com/snail007/gmc/blob/master/README_EN.md Examples of how to set up API routes for GET and POST requests using the GMCT framework. ```APIDOC ### API Routing ```go api, _ := gmc.New.APIServer(gmc.New.Ctx(), ":8080") // GET request api.API("/user/:id", func(c gmc.C) { id := c.Param().ByName("id") c.Write(gmap.M{ "user_id": id, "name": "John Doe", }) }) // POST request api.API("/user", func(c gmc.C) { name := c.Request().FormValue("name") // Handle business logic c.Write(gmap.M{"status": "created", "name": name}) }, "POST") ``` ``` -------------------------------- ### Create Web Application with GMC Source: https://github.com/snail007/gmc/blob/master/README_EN.md Shows how to manually create a simple web application using the GMC framework. This example defines a controller with an index method and sets up an HTTP server to handle requests, returning a welcome message. ```go package main import ( "github.com/snail007/gmc" gcore "github.com/snail007/gmc/core" ) type HomeController struct { gmc.Controller } func (c *HomeController) Index() { c.Write("Welcome to GMC!") } func main() { // Create application app := gmc.New.App() // Create HTTP server s := gmc.New.HTTPServer(app.Ctx()) s.Router().Controller("/", new(HomeController)) // Add service and run app.AddService(gcore.ServiceItem{ Service: s, }) app.Run() } ``` -------------------------------- ### Create Simple API Service with GMC Source: https://github.com/snail007/gmc/blob/master/README_EN.md Illustrates how to manually create a basic API server using the GMC framework. This example demonstrates setting up an API server, defining a root route that returns a JSON response, and running the application. ```go package main import ( "github.com/snail007/gmc" gcore "github.com/snail007/gmc/core" gmap "github.com/snail007/gmc/util/map" ) func main() { // Create API server api, _ := gmc.New.APIServer(gmc.New.Ctx(), ":8080") // Register route api.API("/", func(c gmc.C) { c.Write(gmap.M{ "code": 0, "message": "Hello GMC!", "data": nil, }) }) // Create app and run app := gmc.New.App() app.AddService(gcore.ServiceItem{ Service: api.(gcore.Service), }) app.Run() } ``` -------------------------------- ### API Routing Examples in Go Source: https://github.com/snail007/gmc/blob/master/README.md This Go code illustrates different ways to define API routes using GMC. It shows how to handle GET requests with path parameters and POST requests with form data. The examples utilize GMC's `APIServer` and `gmc.C` context for accessing request parameters and writing responses. ```go api, _ := gmc.New.APIServer(gmc.New.Ctx(), ":8080") // GET 请求 api.API("/user/:id", func(c gmc.C) { id := c.Param().ByName("id") c.Write(gmap.M{ "user_id": id, "name": "John Doe", }) }) // POST 请求 api.API("/user", func(c gmc.C) { name := c.Request().FormValue("name") // 处理业务逻辑 c.Write(gmap.M{"status": "created", "name": name}) }, "POST") ``` -------------------------------- ### Storage Backend Initialization (Manual) Source: https://github.com/snail007/gmc/blob/master/http/session/README.md Demonstrates how to manually initialize different session storage backends without using configuration files. ```APIDOC ## Storage Backend Initialization (Manual) ### Memory Store ```go package main import ( gsession "github.com/snail007/gmc/http/session" ) func main() { cfg := gsession.NewMemoryStoreConfig() cfg.TTL = 3600 // 1 hour cfg.GCtime = 60 // GC every 60 seconds store, err := gsession.NewMemoryStore(cfg) if err != nil { panic(err) } // Use the store... } ``` ### File Store ```go package main import ( gsession "github.com/snail007/gmc/http/session" ) func main() { cfg := gsession.NewFileStoreConfig() cfg.TTL = 3600 cfg.Dir = "./sessions" cfg.Prefix = "sess_" cfg.GCtime = 60 store, err := gsession.NewFileStore(cfg) if err != nil { panic(err) } // Use the store... } ``` ``` -------------------------------- ### Go Get Request Header Examples Source: https://github.com/snail007/gmc/blob/master/docs/zh/MANUAL_ZH.md Explains how to access individual request headers and iterate over all request headers in Go controllers. It shows how to retrieve common headers like Content-Type, User-Agent, and Authorization. ```go func (this *User) Headers() { // 获取单个请求头 contentType := this.Ctx.Header("Content-Type") userAgent := this.Ctx.Header("User-Agent") auth := this.Ctx.Header("Authorization") // 获取所有请求头 headers := this.Request.Header for key, values := range headers { fmt.Printf("%s: %v\n", key, values) } } ``` -------------------------------- ### Create and Run Web Project with GMCT Source: https://github.com/snail007/gmc/blob/master/README_EN.md Demonstrates how to create a new web project using the GMCT toolchain and then run it with hot compilation enabled. This process includes scaffolding the project structure and starting the development server. ```bash # Create Web project mkdir myapp && cd myapp gmct new web # Or create API project gmct new api # Run with hot compilation (recommended for development) gmct run # Visit http://localhost:7080 ``` -------------------------------- ### Transaction Handling Example in Go Source: https://github.com/snail007/gmc/blob/master/docs/zh/MANUAL_ZH.md Illustrates how to manage database transactions using the gmc library. This includes starting a transaction, performing multiple operations within the transaction, handling errors, and committing or rolling back the transaction. ```go func (this *User) TransactionExample() { db := this.GetDB() // 开始事务 tx, err := db.Begin() if err != nil { this.Logger.Error(err) return } // 延迟回滚或提交 defer func() { if r := recover(); r != nil { tx.Rollback() this.Logger.Errorf("事务回滚: %v", r) } }() // 执行操作 ar := db.AR() ar.Insert("users", map[string]interface{}{ "name": "测试用户", }) result, err := db.ExecTx(ar, tx) if err != nil { tx.Rollback() return } userID := result.LastInsertID() // 第二个操作 ar = db.AR() ar.Insert("profiles", map[string]interface{}{ "user_id": userID, "bio": "个人简介", }) _, err = db.ExecTx(ar, tx) if err != nil { tx.Rollback() return } // 提交事务 if err := tx.Commit(); err != nil { this.Logger.Error(err) return } this.Logger.Info("事务提交成功") } ``` -------------------------------- ### Create and Run a GMC Web Service in Go Source: https://github.com/snail007/gmc/blob/master/docs/MANUAL.md This Go code demonstrates how to create a default GMC application, add an HTTP server service, perform custom initialization after the server starts, and then run the application. It utilizes the gmc.New.AppDefault() and gcore.HTTPServer() functions for service creation and gcore.ServiceItem for managing service lifecycle. ```go package main import ( "fmt" "github.com/snail007/gmc" gcore "github.com/snail007/gmc/core" "mygmcweb/initialize" ) func main() { // 1. create an default app to run. app := gmc.New.AppDefault() // 2. add a http server service to app. app.AddService(gcore.ServiceItem{ Service: gmc.New.HTTPServer(app.Ctx()).(gcore.Service), AfterInit: func(s *gcore.ServiceItem) (err error) { // do some initialize after http server initialized. err = initialize.Initialize(s.Service.(gcore.HTTPServer)) return }, }) // 3. run the app if e := gmc.Err.Stack(app.Run()); e != "" { fmt.Println(e) } } ``` -------------------------------- ### UPDATE Operation Examples in Go Source: https://github.com/snail007/gmc/blob/master/docs/zh/MANUAL_ZH.md Shows how to execute UPDATE statements with the gmc library. This includes updating a single record based on a condition and performing batch updates on multiple records. It also demonstrates how to get the number of affected rows. ```go func (this *User) UpdateExamples() { db := this.GetDB() // 更新数据 ar := db.AR() ar.Update("users", map[string]interface{}{ "name": "张三三", "updated_at": time.Now(), }, map[string]interface{}{ "id": 1, }, ) result, err := db.Exec(ar) // 获取受影响的行数 affected := result.RowsAffected() this.Logger.Infof("更新了 %d 行", affected) // 批量更新 ar = db.AR() updates := []map[string]interface{}{ {"id": 1, "status": "active"}, {"id": 2, "status": "inactive"}, } ar.UpdateBatch("users", updates, []string{"id"}) db.Exec(ar) } ``` -------------------------------- ### Go: gbatch 等待首个成功的任务 Source: https://github.com/snail007/gmc/blob/master/util/batch/README.md 展示如何使用 gbatch 的 WaitFirstSuccess() 方法。此方法会并发执行添加的任务,并在其中一个任务成功返回时立即返回其结果,忽略其他任务的执行和结果。如果所有任务都失败,则返回错误。 ```go package main import ( "context" "fmt" "time" "github.com/snail007/gmc/util/batch" ) func main() { executor := gbatch.NewBatchExecutor() // 添加多个任务,只要有一个成功就返回 executor.AppendTask( func(ctx context.Context) (interface{}, error) { time.Sleep(2 * time.Second) return "slow task", nil }, func(ctx context.Context) (interface{}, error) { time.Sleep(100 * time.Millisecond) return "fast task", nil }, func(ctx context.Context) (interface{}, error) { return nil, fmt.Errorf("failed task") }, ) // 等待首个成功的任务 value, err := executor.WaitFirstSuccess() if err != nil { fmt.Printf("All tasks failed: %v\n", err) } else { fmt.Printf("First success: %v\n", value) } } ``` -------------------------------- ### GMC Router Configuration Example Source: https://github.com/snail007/gmc/blob/master/docs/zh/MANUAL_ZH.md This Go code configures the routes for a GMC application. It uses the provided HTTPServer to get a router instance and then binds a controller ('controller.Demo') to a specific path ('/demo'). It also shows how to bind a single controller method to a path. ```go package router import ( "myapp/controller" "github.com/snail007/gmc" ) func Init(s gmc.HTTPServer) { // Get router object r := s.Router() // Bind controller r.Controller("/demo", new(controller.Demo)) // Or bind a single method r.ControllerMethod("/", new(controller.Demo), "Index") } ``` -------------------------------- ### GMC Project Structure Best Practice Source: https://github.com/snail007/gmc/blob/master/http/server/README.md This outlines a recommended project structure for applications built with the GMC framework. It categorizes components like the main entry point (`main.go`), configuration (`app.toml`), controllers, routers, initialization logic, models, views (templates), and static files into distinct directories for better organization and maintainability. ```plaintext myapp/ ├── main.go # 入口 ├── app.toml # 配置 ├── controller/ # 控制器 │ ├── user.go │ └── product.go ├── router/ # 路由配置 │ └── router.go ├── initialize/ # 初始化 │ └── init.go ├── model/ # 数据模型 ├── views/ # 模板 └── static/ # 静态文件 ``` -------------------------------- ### Cache Usage with GMCT (Go) Source: https://github.com/snail007/gmc/blob/master/README_EN.md Demonstrates how to use GMCT's cache module for storing and retrieving data. Examples include initializing the cache, setting key-value pairs with an expiration time, getting values, and deleting keys from the cache. ```go // Initialize cache gmc.Cache.Init(cfg) cache := gmc.Cache.Cache() // Set cache (expires in 60 seconds) cache.Set("key", "value", 60) // Get cache value, exists := cache.Get("key") // Delete cache cache.Del("key") ```