### Manage Configuration with Viper Source: https://context7.com/zjutjh/mygo/llms.txt Provides examples for accessing application settings using the MyGo config package. It supports direct value retrieval, scoped configuration access, and unmarshaling YAML data into Go structs. ```go package main import "github.com/zjutjh/mygo/config" func example() { appName := config.AppName() env := config.AppEnv() cfg := config.Pick() dbHost := cfg.GetString("db.host") var dbConfig DatabaseConfig cfg.UnmarshalKey("db", &dbConfig) } type DatabaseConfig struct { Host string `mapstructure:"host"` Port int `mapstructure:"port"` } ``` -------------------------------- ### Bootstrap Application and CLI Commands in Go Source: https://context7.com/zjutjh/mygo/llms.txt Demonstrates how to initialize the MyGo kernel with service boot functions and register custom CLI commands using the Cobra library. This pattern ensures services like logging, databases, and caching are prepared before application execution. ```go package main import ( "github.com/spf13/cobra" "github.com/zjutjh/mygo/foundation/command" "github.com/zjutjh/mygo/foundation/kernel" "github.com/zjutjh/mygo/ndb" "github.com/zjutjh/mygo/nedis" "github.com/zjutjh/mygo/nlog" ) func main() { command.Execute( func() kernel.BootList { return kernel.BootList{ nlog.Boot("access_log", "error_log"), ndb.Boot("secondary_db"), nedis.Boot("cache_redis"), } }, func(root *cobra.Command) { command.Add("migrate", func(cmd *cobra.Command, args []string) error { return nil }) }, nil, ) } ``` -------------------------------- ### Integrate WeChat Mini Program API in Go Source: https://context7.com/zjutjh/mygo/llms.txt Demonstrates how to initialize the Mini Program client to perform authentication, retrieve access tokens, send subscription messages, and generate unlimited QR codes. Requires a configured environment with Redis and Resty support. ```go package main import ( "github.com/zjutjh/mygo/wechat/miniProgram" ) func example() { mp := miniProgram.Pick() session, err := mp.Auth.Session(ctx, "user-login-code") if err != nil { // Handle error } openID := session.OpenID token, err := mp.AccessToken.GetToken(ctx, false) mp.SubscribeMessage.Send(ctx, &request.RequestSubscribeMessageSend{ ToUser: openID, TemplateID: "template-id", Data: map[string]*request.SubscribeMessageData{ "thing1": {Value: "Order Confirmed"}, "time2": {Value: "2024-01-15 10:30"}, }, }) qrResp, err := mp.WXACode.GetUnlimited(ctx, &request.RequestWXACodeGetUnlimited{ Scene: "user=123", Page: "pages/index/index", }) } ``` -------------------------------- ### Implement HTTP Server and Routing with Gin Source: https://context7.com/zjutjh/mygo/llms.txt Shows how to wrap a Gin engine within the MyGo framework to handle HTTP requests. It includes route registration, middleware application, and structured JSON responses using the framework's reply utility. ```go package main import ( "github.com/gin-gonic/gin" "github.com/zjutjh/mygo/foundation/command" "github.com/zjutjh/mygo/foundation/httpserver" "github.com/zjutjh/mygo/foundation/kernel" "github.com/zjutjh/mygo/foundation/reply" "github.com/zjutjh/mygo/kit" "github.com/zjutjh/mygo/middleware/cors" ) func main() { command.Execute( func() kernel.BootList { return kernel.BootList{} }, func(root *cobra.Command) { command.Add("server", httpserver.CommandRegister(registerRoutes)) }, httpserver.CommandRegister(registerRoutes), ) } func registerRoutes(engine *gin.Engine) { engine.Use(cors.Pick()) api := engine.Group("/api") { api.GET("/health", func(ctx *gin.Context) { reply.Success(ctx, gin.H{"status": "ok"}) }) } } ``` -------------------------------- ### Go Standard API Response Formatting Source: https://context7.com/zjutjh/mygo/llms.txt This Go code snippet shows how to use the 'reply' package to send standardized JSON responses for HTTP APIs. It covers success responses, error responses using predefined codes, custom error responses, and responses with custom codes and data. Dependencies include 'github.com/gin-gonic/gin' for HTTP handling and custom packages 'github.com/zjutjh/mygo/foundation/reply' and 'github.com/zjutjh/mygo/kit' for reply formatting and error codes. ```go package main import ( "github.com/gin-gonic/gin" "github.com/zjutjh/mygo/foundation/reply" "github.com/zjutjh/mygo/kit" ) func handler(ctx *gin.Context) { // Success response // {"code": 0, "message": "Success", "data": {"id": 1, "name": "John"}} reply.Success(ctx, gin.H{ "id": 1, "name": "John", }) // Error response with predefined codes // {"code": 20003, "message": "Invalid parameter", "data": null} reply.Fail(ctx, kit.CodeParameterInvalid) // Custom error response // {"code": 30001, "message": "Custom error", "data": null} customCode := kit.NewCode(30001, "Custom error message") reply.Fail(ctx, customCode) // Response with custom code and data reply.Reply(ctx, kit.CodeOK, gin.H{"result": "processed"}) } // Predefined error codes // kit.CodeOK - 0: Success // kit.CodeUnknownError - 10000: Unknown error // kit.CodeThirdServiceError - 10001: Third-party service error // kit.CodeDatabaseError - 10002: Database error // kit.CodeRedisError - 10003: Redis error // kit.CodeNotLoggedIn - 20000: User not logged in // kit.CodeLoginExpired - 20001: Login expired // kit.CodePermissionDenied - 20002: Permission denied // kit.CodeParameterInvalid - 20003: Invalid parameter // kit.CodeDataNotFound - 20005: Data not found // kit.CodeTooFrequently - 20008: Too frequent requests ``` -------------------------------- ### Implement Redis Client with Multi-Mode Support in Go Source: https://context7.com/zjutjh/mygo/llms.txt The nedis package provides a wrapper for Redis clients supporting single, cluster, and failover modes. It includes features for connection pooling, pipelining, and Pub/Sub messaging. ```go package main import ( "context" "time" "github.com/zjutjh/mygo/foundation/kernel" "github.com/zjutjh/mygo/nedis" ) func bootRedis() kernel.BootList { return kernel.BootList{ nedis.Boot("session_redis", "cache_redis"), } } func example() { ctx := context.Background() rdb := nedis.Pick() cacheRDB := nedis.Pick("cache_redis") rdb.Set(ctx, "user:1:name", "John", 24*time.Hour) val, _ := rdb.Get(ctx, "user:1:name").Result() rdb.HSet(ctx, "user:1", map[string]interface{}{ "name": "John", "email": "john@example.com", }) pipe := rdb.Pipeline() pipe.Incr(ctx, "counter") pipe.Exec(ctx) } ``` -------------------------------- ### Generate OpenAPI Documentation with Swagger in Go Source: https://context7.com/zjutjh/mygo/llms.txt Uses struct tags to define API contracts and automatically generate Swagger documentation for Gin routes. Developers register API structs in the swagger.CM map to expose endpoints via the DocumentHandler. ```go package main import ( "github.com/gin-gonic/gin" "github.com/zjutjh/mygo/swagger" ) func init() { swagger.CM["main.createUser"] = CreateUserAPI{} } type CreateUserAPI struct { Info struct{} `name:"Create User" desc:"Creates a new user account"` Body struct { Name string `json:"name" binding:"required" description:"User's full name"` Email string `json:"email" binding:"required,email" description:"User's email address"` } Response struct { ID uint `json:"id" description:"Created user ID"` } } func registerRoutes(engine *gin.Engine) { engine.GET("/swagger", swagger.DocumentHandler(engine)) } ``` -------------------------------- ### JWT Authentication with Go Source: https://context7.com/zjutjh/mygo/llms.txt Implements JWT token generation, parsing, and middleware for securing API routes. It supports configurable claims like expiration, issuer, and audience, and integrates with the Gin framework. Dependencies include the Gin framework and custom JWT packages. ```go package main import ( "github.com/gin-gonic/gin" "github.com/zjutjh/mygo/foundation/kernel" "github.com/zjutjh/mygo/jwt" jwtMiddleware "github.com/zjutjh/mygo/jwt/middleware" ) // config.yaml: // jwt: // secret: "your-secret-key" // issuer: "myapp" // audience: ["web", "mobile"] // expiration: "24h" type UserIdentity struct { UserID uint `json:"user_id"` Username string `json:"username"` Role string `json:"role"` } func bootJWT() kernel.BootList { return kernel.BootList{ jwt.Boot[UserIdentity]("admin_jwt"), // Boot default + named instances } } func example() { // Get JWT instance j := jwt.Pick[UserIdentity]() // Generate token identity := UserIdentity{ UserID: 1, Username: "john", Role: "admin", } token, err := j.GenerateToken(identity) if err != nil { // Handle error } // token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." // Parse token parsedIdentity, err := j.ParseToken(token) if err != nil { // Handle error (expired, invalid, etc.) } // parsedIdentity.UserID == 1 } func registerRoutes(engine *gin.Engine) { // Public routes engine.POST("/login", loginHandler) // Protected routes with JWT middleware protected := engine.Group("/api") protected.Use(jwtMiddleware.Auth[UserIdentity](true)) // mustLogged = true { protected.GET("/profile", func(ctx *gin.Context) { // Get identity from context identity, err := jwt.GetIdentity[UserIdentity](ctx) if err != nil { // Handle error return } // Use identity.UserID, identity.Username, etc. }) } // Optional auth (logged in users get extra features) optional := engine.Group("/public") optional.Use(jwtMiddleware.Auth[UserIdentity](false)) // mustLogged = false { optional.GET("/content", contentHandler) } } ``` -------------------------------- ### Session Management with Go Source: https://context7.com/zjutjh/mygo/llms.txt Provides cookie-based session management using Redis or in-memory storage. It integrates with the Gin framework, allowing for secure session data handling and route protection. Configuration options include driver, secret, and cookie parameters. ```go package main import ( "github.com/gin-gonic/gin" "github.com/zjutjh/mygo/session" sessionMiddleware "github.com/zjutjh/mygo/session/middleware" ) // config.yaml: // session: // driver: "redis" // redis or memory // redis: "redis" // Redis config scope // secret: "session-secret" // name: "session_id" // path: "/" // domain: "" // max_age: 86400 // secure: false // http_only: true type SessionUser struct { UserID uint Username string } func registerRoutes(engine *gin.Engine) { // Apply session middleware engine.Use(session.Pick()) engine.POST("/login", func(ctx *gin.Context) { // Authenticate user... user := SessionUser{UserID: 1, Username: "john"} // Set session identity if err := session.SetIdentity(ctx, user); err != nil { // Handle error return } // Session cookie is automatically set }) engine.POST("/logout", func(ctx *gin.Context) { // Delete session identity if err := session.DeleteIdentity(ctx); err != nil { // Handle error return } }) // Protected routes protected := engine.Group("/api") protected.Use(sessionMiddleware.Auth[SessionUser](true)) { protected.GET("/me", func(ctx *gin.Context) { // Get session identity user, err := session.GetIdentity[SessionUser](ctx) if err != nil { // Handle error return } // Use user.UserID, user.Username }) } } ``` -------------------------------- ### Schedule Cron Jobs in Go Source: https://context7.com/zjutjh/mygo/llms.txt Utilizes the robfig/cron package to register and execute scheduled tasks. Supports cron expressions with seconds and custom job structures for complex logic. ```Go package main import ( "github.com/robfig/cron/v3" "github.com/spf13/cobra" "github.com/zjutjh/mygo/foundation/command" "github.com/zjutjh/mygo/foundation/crontab" "github.com/zjutjh/mygo/foundation/kernel" ) func main() { command.Execute( func() kernel.BootList { return kernel.BootList{} }, func(root *cobra.Command) { command.Add("cron", crontab.CommandRegister(registerJobs)) }, nil, ) } func registerJobs(c *cron.Cron) { c.AddFunc("* * * * * *", func() {}) c.AddFunc("0 0 * * * *", cleanupExpiredSessions) c.AddFunc("0 30 2 * * *", generateDailyReport) c.AddFunc("0 0 9 * * 1", sendWeeklyNewsletter) c.AddJob("0 */5 * * * *", &DataSyncJob{}) } type DataSyncJob struct{} func (j *DataSyncJob) Run() {} func cleanupExpiredSessions() {} func generateDailyReport() {} func sendWeeklyNewsletter() {} ``` -------------------------------- ### Structured Logging with Logrus Source: https://context7.com/zjutjh/mygo/llms.txt Implements structured JSON logging with features like log rotation, Feishu webhook alerts for critical logs, and multi-instance support. It requires the 'nlog' package and can be configured via 'config.yaml'. ```go package main import ( "github.com/zjutjh/mygo/foundation/kernel" "github.com/zjutjh/mygo/nlog" ) // config.yaml: // log: // filename: "logs/app.log" // max_size: 100 # MB // max_age: 30 # days // max_backups: 10 // local_time: true // compress: true // level: 4 # Debug=5, Info=4, Warn=3, Error=2 // feishu_hook: // feishu: "feishu" # Feishu config scope // notice_levels: [2, 3] # Error and Warn func bootLogging() kernel.BootList { return kernel.BootList{ nlog.Boot("access_log", "error_log"), } } func example() { // Get default logger logger := nlog.Pick() // Get named logger accessLog := nlog.Pick("access_log") // Basic logging logger.Info("Application started") logger.Debug("Debug information") logger.Warn("Warning message") logger.Error("Error occurred") // Structured logging with fields logger.WithField("user_id", 123).Info("User logged in") logger.WithFields(map[string]interface{}{ "request_id": "abc123", "method": "POST", "path": "/api/users", "latency": "45ms", }).Info("Request completed") // Error logging with error object err := someOperation() if err != nil { logger.WithError(err).Error("Operation failed") } // Formatted logging logger.Infof("Processing %d items", 100) logger.Errorf("Failed to connect to %s: %v", "database", err) } ``` -------------------------------- ### HTTP Client with Resty Source: https://context7.com/zjutjh/mygo/llms.txt A wrapper around the go-resty HTTP client, offering automatic logging, retry logic, and configurable timeouts. It depends on the 'nesty' package and can be configured via 'config.yaml'. ```go package main import ( "github.com/zjutjh/mygo/nesty" ) // config.yaml: // resty: // log: "log" // timeout: "30s" // retry_count: 3 // retry_wait_time: "100ms" // retry_max_wait_time: "2s" func example() { client := nesty.Pick() // GET request var result map[string]interface{} resp, err := client.R(). SetHeader("Accept", "application/json"). SetQueryParam("page", "1"). SetResult(&result). Get("https://api.example.com/users") if err != nil { // Handle error } if resp.IsError() { // Handle HTTP error (4xx, 5xx) } // POST request with JSON body type CreateRequest struct { Name string `json:"name"` Email string `json:"email"` } type CreateResponse struct { ID int `json:"id"` Name string `json:"name"` } var createResp CreateResponse resp, err = client.R(). SetHeader("Content-Type", "application/json"). SetBody(CreateRequest{Name: "John", Email: "john@example.com"}). SetResult(&createResp). Post("https://api.example.com/users") // Form data resp, err = client.R(). SetFormData(map[string]string{ "username": "john", "password": "secret", }). Post("https://api.example.com/login") // File upload resp, err = client.R(). SetFile("file", "/path/to/file.pdf"). SetFormData(map[string]string{"description": "My document"}). Post("https://api.example.com/upload") } ``` -------------------------------- ### Manage MySQL Database Connections with GORM in Go Source: https://context7.com/zjutjh/mygo/llms.txt The ndb package facilitates MySQL connectivity using GORM. It supports multi-instance configurations, connection pooling, and standard GORM operations like transactions and queries. ```go package main import ( "github.com/zjutjh/mygo/foundation/kernel" "github.com/zjutjh/mygo/ndb" ) type User struct { ID uint `gorm:"primaryKey"` Name string `gorm:"size:255"` Email string `gorm:"uniqueIndex"` } func bootDatabase() kernel.BootList { return kernel.BootList{ ndb.Boot("analytics_db", "logs_db"), } } func example() { db := ndb.Pick() analyticsDB := ndb.Pick("analytics_db") if ndb.Exist("logs_db") { logsDB := ndb.Pick("logs_db") } user := User{Name: "John", Email: "john@example.com"} result := db.Create(&user) var users []User db.Where("name LIKE ?", "%John%").Find(&users) db.Transaction(func(tx *gorm.DB) error { return tx.Create(&User{Name: "Alice"}).Error }) } ``` -------------------------------- ### Manage Files with Cube Storage Client in Go Source: https://context7.com/zjutjh/mygo/llms.txt Enables file operations including uploading from bytes or disk, generating public URLs, and deleting files from the Cube storage service. ```Go package main import ( "bytes" "context" "os" "github.com/zjutjh/mygo/cube" ) func example() { client := cube.Pick() ctx := context.Background() // Upload resp, _ := client.UploadFile(ctx, "hello.txt", bytes.NewReader([]byte("Hello")), "docs/", false, true) objectKey := resp.Data.ObjectKey // Retrieve URLs fileURL := client.GetFileURL(objectKey, false) // Delete client.DeleteFile(objectKey) } ``` -------------------------------- ### Distributed Locking with Redsync Source: https://context7.com/zjutjh/mygo/llms.txt Provides distributed locking capabilities using Redsync, which relies on Redis for mutual exclusion in distributed systems. It requires the 'lock' package and Redis configuration. ```go package main import ( "context" "time" "github.com/go-redsync/redsync/v4" "github.com/zjutjh/mygo/foundation/kernel" "github.com/zjutjh/mygo/lock" ) // config.yaml: // lock: // redis: "redis" # Redis config scope func bootLock() kernel.BootList { return kernel.BootList{ lock.Boot(), } } func example() { rs := lock.Pick() // Create a mutex for a specific resource mutex := rs.NewMutex("order:123:process", redsync.WithExpiry(30*time.Second), redsync.WithTries(3), redsync.WithRetryDelay(100*time.Millisecond), ) // Acquire lock if err := mutex.Lock(); err != nil { // Failed to acquire lock (resource is busy) return } defer mutex.Unlock() // Critical section - only one process can execute this processOrder("123") // Lock with context ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if err := mutex.LockContext(ctx); err != nil { // Lock acquisition timed out or failed return } defer mutex.Unlock() } func processOrder(orderID string) { // Process order logic } ``` -------------------------------- ### Integrate WeChat Official Account API in Go Source: https://context7.com/zjutjh/mygo/llms.txt Provides methods for OAuth flow management, template message delivery, and media material uploads within the WeChat Official Account ecosystem. ```go package main import ( "github.com/zjutjh/mygo/wechat/officialAccount" ) func example() { oa := officialAccount.Pick() authURL, err := oa.OAuth.GetAuthURL(redirectURI, "snsapi_userinfo", "state") user, err := oa.OAuth.UserFromCode(code) openID := user.GetOpenID() oa.TemplateMessage.Send(ctx, &request.RequestTemplateSend{ ToUser: openID, TemplateID: "template-id", URL: "https://example.com/detail", Data: map[string]*request.TemplateData{ "first": {Value: "Your order has been shipped"}, "keyword1": {Value: "Order #12345"}, }, }) mediaResp, err := oa.Material.MediaUpload(ctx, mediaType, filePath) } ``` -------------------------------- ### Send Feishu Bot Notifications in Go Source: https://context7.com/zjutjh/mygo/llms.txt Provides a client to send webhook notifications to Feishu (Lark). Supports checking configuration existence and using named client instances for different alert channels. ```Go package main import "github.com/zjutjh/mygo/feishu" func example() { if !feishu.Exist() { return } client := feishu.Pick() err := client.Send("[MyApp] Alert", "Database connection failed!") if feishu.Exist("alerts") { alertClient := feishu.Pick("alerts") alertClient.Send("[Critical]", "Service is down!") } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.