### Quick Start with Docker Compose Source: https://github.com/go-nunu/nunu/blob/main/docs/en/guide.md Quickly set up and run an advanced Nunu project layout using Docker Compose. This includes starting services, running migrations, and starting the server. ```bash cd ./deploy/docker-compose && docker compose up -d && cd ../.. go run ./cmd/migration nunu run ./cmd/server ``` ```bash make bootstrap ``` -------------------------------- ### Install golang/mock Source: https://github.com/go-nunu/nunu/blob/main/docs/en/unit_testing.md Install the mockgen tool for generating mock code from interface definitions. ```bash go install github.com/golang/mock/mockgen@v1.6.0 ``` -------------------------------- ### Example local.yaml Configuration Source: https://github.com/go-nunu/nunu/blob/main/docs/en/guide.md This YAML file shows how to configure database and Redis connection details. ```yaml data: mysql: user: root:123456@tcp(127.0.0.1:3380)/user?charset=utf8mb4&parseTime=True&loc=Local redis: addr: 127.0.0.1:6350 password: "" db: 0 read_timeout: 0.2s write_timeout: 0.2s ``` -------------------------------- ### Start Nunu Project with Migrations Source: https://github.com/go-nunu/nunu/blob/main/docs/en/tutorial.md Commands to run database migrations and start the Nunu server. Ensure configuration files are updated before running. ```bash // Please modify the MySQL and Redis configuration information in config/local.yml before starting the server // Before starting the server for the first time, run the following database migration nunu run ./cmd/migration // Start the server nunu run ./cmd/server // Or nunu run // Or nunu run ./cmd/server --excludeDir=".git,.idea,tmp,vendor" --includeExt="go,yml,vue" -- --conf=./config/local.yml ``` -------------------------------- ### Install Nunu CLI Source: https://github.com/go-nunu/nunu/blob/main/README.md Installs the Nunu command-line interface tool. Ensure Go 1.19 or higher is installed. If the command is not recognized after installation, add the GOBIN directory to your environment variables. ```bash go install github.com/go-nunu/nunu@latest ``` -------------------------------- ### Register HTTP Route with Handler Source: https://github.com/go-nunu/nunu/blob/main/docs/en/tutorial.md Example of registering a GET route for '/order' that uses the OrderHandler. This involves adding the handler dependency and defining the route in the HTTP server setup. ```go func NewServerHTTP( // ... handler *handler.OrderHandler, // new ) *gin.Engine { // ... // No authentication routes noAuthRouter := r.Group("/").Use(middleware.RequestLogMiddleware(logger)) { noAuthRouter.GET("/order", handler.GetOrderById) // new ``` -------------------------------- ### Interface-Oriented Programming Example Source: https://github.com/go-nunu/nunu/blob/main/docs/en/guide.md Illustrates the Nunu pattern of using interfaces for repository definitions to enhance flexibility and testability. ```go type UserRepository interface { FirstById(id int64) (*model.User, error) } type userRepository struct { *Repository } ``` -------------------------------- ### Example Logging Configuration Source: https://github.com/go-nunu/nunu/blob/main/docs/en/guide.md This YAML configuration specifies settings for Nunu's Zap-based logging system. ```yaml log: log_level: info encoding: json # json or console log_file_name: "./storage/logs/server.log" max_backups: 30 # Maximum number of log file backups max_age: 7 # Maximum number of days to keep files max_size: 1024 # Maximum size of each log file in MB compress: true # Whether to compress the log files ``` -------------------------------- ### Start Nunu with Specific Configuration Source: https://github.com/go-nunu/nunu/blob/main/docs/en/guide.md Run the Nunu project using a specific configuration file. This can be done by setting the APP_CONF environment variable or using a command-line parameter. ```bash # Linux or MacOS APP_CONF=config/prod.yml nunu run # Windows set APP_CONF=config\prod.yml && nunu run ``` ```bash go run ./cmd/server -conf=config/prod.yml ``` -------------------------------- ### Dependency Injection Example (wire.go) Source: https://github.com/go-nunu/nunu/blob/main/docs/en/unit_testing.md This snippet shows the dependency graph generated by google/wire, illustrating the relationships between handlers, services, and repositories in the Nunu server. ```go // Injectors from wire.go: func newApp(viperViper *viper.Viper, logger *log.Logger) (*gin.Engine, func(), error) { jwt := middleware.NewJwt(viperViper) handlerHandler := handler.NewHandler(logger) sidSid := sid.NewSid() serviceService := service.NewService(logger, sidSid, jwt) db := repository.NewDB(viperViper) client := repository.NewRedis(viperViper) repositoryRepository := repository.NewRepository(db, client, logger) userRepository := repository.NewUserRepository(repositoryRepository) userService := service.NewUserService(serviceService, userRepository) userHandler := handler.NewUserHandler(handlerHandler, userService) engine := server.NewServerHTTP(logger, jwt, userHandler) return engine, func() { }, nil } ``` -------------------------------- ### Nunu Component Creation Log Source: https://github.com/go-nunu/nunu/blob/main/docs/en/tutorial.md Example log output indicating the successful creation of handler, service, repository, and model files for a component. ```bash // Log information Created new handler: internal/handler/order.go Created new service: internal/service/order.go Created new repository: internal/repository/order.go Created new model: internal/model/order.go ``` -------------------------------- ### Define Wire Providers for Nunu Components Source: https://github.com/go-nunu/nunu/blob/main/docs/en/tutorial.md Example of defining Wire provider sets for Nunu components, including handlers, services, and repositories. This is part of the dependency injection setup. ```go //go:build wireinject // +build wireinject package main // ... var HandlerSet = wire.NewSet( handler.NewHandler, handler.NewUserHandler, handler.NewOrderHandler, // new ) var ServiceSet = wire.NewSet( service.NewService, sservice.NewUserService, sservice.NewOrderService, // new ) var RepositorySet = wire.NewSet( repository.NewDB, repository.NewRedis, repository.NewRepository, repository.NewUserRepository, repository.NewOrderRepository, // new ) func newApp(*viper.Viper, *log.Logger) (*gin.Engine, func(), error) { panic(wire.Build( ServerSet, RepositorySet, ServiceSet, HandlerSet, SidSet, JwtSet, )) } ``` -------------------------------- ### Install Swag CLI Source: https://github.com/go-nunu/nunu/blob/main/docs/en/tutorial.md Install the swag command-line tool, which is used for automatically generating OpenAPI documentation from code comments. ```bash go install github.com/swaggo/swag/cmd/swag@latest ``` -------------------------------- ### Interface-Oriented Programming Example Source: https://github.com/go-nunu/nunu/blob/main/docs/en/unit_testing.md Illustrates the structure of interface-oriented programming in Go, contrasting it with a direct implementation approach. This pattern is crucial for effective mocking. ```go type UserRepository interface { FirstById(id int64) (*model.User, error) } type userRepository struct { *Repository } func (r *userRepository) FirstById(id int64) (*model.User, error) { // ... } ``` -------------------------------- ### Setup Repository with sqlmock and redismock Source: https://github.com/go-nunu/nunu/blob/main/docs/en/unit_testing.md Helper function to set up repository dependencies using sqlmock for database interactions and redismock for Redis. Avoids connecting to real external services during tests. ```go func setupRepository(t *testing.T) (repository.UserRepository, sqlmock.Sqlmock) { mockDB, mock, err := sqlmock.New() if err != nil { t.Fatalf("failed to create sqlmock: %v", err) } db, err := gorm.Open(mysql.New(mysql.Config{ Conn: mockDB, SkipInitializeWithVersion: true, }), &gorm.Config{}) if err != nil { t.Fatalf("failed to open gorm connection: %v", err) } rdb, _ := redismock.NewClientMock() repo := repository.NewRepository(db, rdb, nil) userRepo := repository.NewUserRepository(repo) return userRepo, mock } ``` -------------------------------- ### Run Nunu Project Source: https://github.com/go-nunu/nunu/blob/main/README.md Starts the Nunu project. This command supports hot-reloading, automatically recompiling and restarting the application when files are changed. ```bash nunu run ``` -------------------------------- ### Configure Go Proxy for China Users Source: https://github.com/go-nunu/nunu/blob/main/docs/en/tutorial.md Sets environment variables for Go modules and proxy to speed up installations for users in China. ```bash go env -w GO111MODULE=on go env -w GOPROXY=https://goproxy.cn,direct ``` -------------------------------- ### Handler Function Example (user.go) Source: https://github.com/go-nunu/nunu/blob/main/docs/en/unit_testing.md This Go code demonstrates a typical handler function that calls a service layer. It includes basic error handling for unauthorized access and service errors. ```go func (h *userHandler) GetProfile(ctx *gin.Context) { userId := GetUserIdFromCtx(ctx) if userId == "" { v1.HandleError(ctx, http.StatusUnauthorized, 1, "unauthorized", nil) return } user, err := h.userService.GetProfile(ctx, userId) if err != nil { v1.HandleError(ctx, http.StatusBadRequest, 1, err.Error(), nil) return } resp.HandleSuccess(ctx, user) } ``` -------------------------------- ### Generated Wire Dependency Code Source: https://github.com/go-nunu/nunu/blob/main/docs/en/tutorial.md This is an example of the dependency injection code automatically generated by Wire for services and handlers. ```go func NewApp(viperViper *viper.Viper, logger *log.Logger) (*gin.Engine, func(), error) { jwt := middleware.NewJwt(viperViper) handlerHandler := handler.NewHandler(logger) sidSid := sid.NewSid() serviceService := service.NewService(logger, sidSid, jwt) db := repository.NewDB(viperViper) client := repository.NewRedis(viperViper) repositoryRepository := repository.NewRepository(db, client, logger) userRepository := repository.NewUserRepository(repositoryRepository) userService := service.NewUserService(serviceService, userRepository) userHandler := handler.NewUserHandler(handlerHandler, userService) orderRepository := repository.NewOrderRepository(repositoryRepository) orderService := service.NewOrderService(serviceService, orderRepository) orderHandler := handler.NewOrderHandler(handlerHandler, orderService) engine := server.NewServerHTTP(logger, jwt, userHandler, orderHandler) return engine, func() { }, nil } ``` -------------------------------- ### Example Swagger Handler Comment Source: https://github.com/go-nunu/nunu/blob/main/docs/en/tutorial.md This Go code demonstrates how to add comments to handler functions to enable automatic Swagger documentation generation. These comments define the API's summary, description, tags, and routing. ```go // GetProfile godoc // @Summary get user info. // @Schemes // @Description // @Tags 用户模块 // @Accept json // @Produce json // @Security Bearer // @Success 200 {object} response.Response // @Router /user [get] func (h *userHandler) GetProfile(ctx *gin.Context) { // ... } ``` -------------------------------- ### Unit Test Repository with Mocked Database Query Source: https://github.com/go-nunu/nunu/blob/main/docs/en/unit_testing.md Example of unit testing a repository's data retrieval method using sqlmock. It mocks the expected SQL query and its return rows. ```go func TestUserRepository_GetByUsername(t *testing.T) { userRepo, mock := setupRepository(t) ctx := context.Background() username := "test" // Simulate querying test data rows := sqlmock.NewRows([]string{"id", "user_id", "username", "nickname", "password", "email", "created_at", "updated_at"}). AddRow(1, "123", "test", "Test", "password", "test@example.com", time.Now(), time.Now()) mock.ExpectQuery("SELECT \* FROM `users`").WillReturnRows(rows) user, err := userRepo.GetByUsername(ctx, username) assert.NoError(t, err) assert.NotNil(t, user) assert.Equal(t, "test", user.Username) assert.NoError(t, mock.ExpectationsWereMet()) } ``` -------------------------------- ### Unit Test Handler with Mocked Service Source: https://github.com/go-nunu/nunu/blob/main/docs/en/unit_testing.md Example of unit testing a handler by mocking its service dependency. This ensures the handler logic is tested in isolation. ```go func TestUserHandler_GetProfile(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() mockUserService := mock_service.NewMockUserService(ctrl) // Key code, define the return value of mockUserService.GetProfile mockUserService.EXPECT().GetProfile(gomock.Any(), userId).Return(&model.User{ Id: 1, UserId: userId, Username: "xxxxx", Nickname: "xxxxx", Password: "xxxxx", Email: "xxxxx@gmail.com", }, nil) router := setupRouter(mockUserService) req, _ := http.NewRequest("GET", "/user", nil) req.Header.Set("Authorization", "Bearer "+token) resp := httptest.NewRecorder() router.ServeHTTP(resp, req) assert.Equal(t, resp.Code, http.StatusOK) // Add assertions for the response body if needed } ``` -------------------------------- ### Repository Initialization with Viper Source: https://github.com/go-nunu/nunu/blob/main/docs/en/guide.md Demonstrates how to initialize database and Redis clients using configuration from Viper. ```go package repository import ( "context" "fmt" "github.com/go-nunu/nunu-layout-advanced/pkg/log" "github.com/redis/go-redis/v9" "github.com/spf13/viper" "gorm.io/driver/mysql" "gorm.io/gorm" time "time" ) type Repository struct { db *gorm.DB rdb *redis.Client logger *log.Logger } func NewRepository(db *gorm.DB, rdb *redis.Client, logger *log.Logger) *Repository { return &Repository{ db: db, rdb: rdb, logger: logger, } } func NewDB(conf *viper.Viper) *gorm.DB { db, err := gorm.Open(mysql.Open(conf.GetString("data.mysql.user")), &gorm.Config{}) if err != nil { panic(err) } return db } func NewRedis(conf *viper.Viper) *redis.Client { rdb := redis.NewClient(&redis.Options{ Addr: conf.GetString("data.redis.addr"), Password: conf.GetString("data.redis.password"), DB: conf.GetInt("data.redis.db"), }) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() _, err := rdb.Ping(ctx).Result() if err != nil { panic(fmt.Sprintf("redis error: %s", err.Error())) } return rdb } ``` -------------------------------- ### Create New Project Source: https://github.com/go-nunu/nunu/blob/main/README.md Generates a new Go project with a standard structure. You can specify a custom template repository for different project layouts. ```bash nunu new projectName ``` ```bash nunu new projectName -r https://gitee.com/go-nunu/nunu-layout-basic.git ``` ```bash nunu new projectName -r https://gitee.com/go-nunu/nunu-layout-advanced.git ``` ```bash nunu new projectName -r https://github.com/go-nunu/nunu-layout-monorepo.git ``` -------------------------------- ### Create Project Components Source: https://github.com/go-nunu/nunu/blob/main/README.md Generates common project components like handlers, services, repositories, and models. The 'all' option creates all component types for a given name. ```bash nunu create handler user ``` ```bash nunu create service user ``` ```bash nunu create repository user ``` ```bash nunu create model user ``` ```bash nunu create all user ``` -------------------------------- ### Create a New Nunu Project with Accelerated Repository Source: https://github.com/go-nunu/nunu/blob/main/docs/en/tutorial.md Creates a new Nunu project using an accelerated repository, either the advanced or basic layout. Recommended for faster downloads in China. ```bash // Using the advanced template (recommended) nunu new projectName -r https://gitee.com/go-nunu/nunu-layout-advanced.git // Using the basic template nunu new projectName -r https://gitee.com/go-nunu/nunu-layout-basic.git ``` -------------------------------- ### Create a New Nunu Project Source: https://github.com/go-nunu/nunu/blob/main/docs/en/tutorial.md Creates a new Nunu project with the specified name. Uses the advanced layout by default. ```bash nunu new projectName ``` -------------------------------- ### Generate Swagger Documentation Source: https://github.com/go-nunu/nunu/blob/main/docs/en/tutorial.md Run this command to generate Swagger documentation files based on your Go code comments. The `-g` flag specifies the main entry point, and `-o` specifies the output directory. ```bash swag init -g cmd/server/main.go -o ./docs --parseDependency // or make swag ``` -------------------------------- ### Nunu Project Directory Structure Source: https://github.com/go-nunu/nunu/blob/main/docs/en/architecture.md Illustrates the organization of files and directories within the Nunu project, highlighting key components like cmd, internal, and pkg. ```tree . ├── api │ └── v1 ├── cmd │ ├── migration │ ├── server │ │ ├── wire │ │ │ ├── wire.go │ │ │ └── wire_gen.go │ │ └── main.go │ └── task ├── config ├── deploy ├── docs ├── internal │ ├── handler │ ├── middleware │ ├── model │ ├── repository │ ├── server │ └── service ├── pkg ├── scripts ├── test │ ├── mocks │ └── server ├── web ├── Makefile ├── go.mod └── go.sum ``` -------------------------------- ### Create Nunu Components Source: https://github.com/go-nunu/nunu/blob/main/docs/en/tutorial.md Generates Handler, Service, Repository, and Model components for a given component name. This command automates the creation of common files and structures. ```bash nunu create all order ``` -------------------------------- ### Create Nunu Project Components Source: https://github.com/go-nunu/nunu/blob/main/docs/en/guide.md Generate common project components like handlers, services, repositories, and models. You can specify custom directories for component creation. ```bash nunu create handler user nunu create service user nunu create repository user nunu create model user ``` ```bash nunu create handler internal/handler/user/center nunu create service internal/service/user/center nunu create repository internal/repository/user/center nunu create model internal/model/user/center ``` ```bash nunu create all user ``` -------------------------------- ### Database Connection and Repository Implementation Source: https://github.com/go-nunu/nunu/blob/main/docs/en/guide.md This Go code defines a UserRepository interface and its implementation for fetching a user by ID using GORM. ```go package repository import ( "github.com/go-nunu/nunu-layout-advanced/internal/model" ) type UserRepository interface { FirstById(id int64) (*model.User, error) } type userRepository struct { *Repository } func NewUserRepository(repository *Repository) *UserRepository { return &UserRepository{ Repository: repository, } } func (r *userRepository) FirstById(id int64) (*model.User, error) { var user model.User if err := r.db.Where("id = ?", id).First(&user).Error; err != nil { return nil, err } return &user, nil } ``` -------------------------------- ### Compile Wire Dependencies Source: https://github.com/go-nunu/nunu/blob/main/docs/en/tutorial.md Use this command to generate dependency injection code for your project. This command generates the `wire_gen.go` file. ```bash nunu wire all ``` -------------------------------- ### Running Unit Tests and Generating Coverage Source: https://github.com/go-nunu/nunu/blob/main/docs/en/guide.md This bash command executes unit tests and generates an HTML coverage report for the Nunu project. ```bash go test -coverpkg=./internal/handler,./internal/service,./internal/repository -coverprofile=./.nunu/coverage.out ./test/server/... go tool cover -html=./.nunu/coverage.out -o coverage.html ``` -------------------------------- ### Define Repository Interface and Implementation Source: https://github.com/go-nunu/nunu/blob/main/docs/en/unit_testing.md This Go code defines a UserRepository interface and its implementation. It demonstrates interface-oriented programming, a prerequisite for using mocking libraries like golang/mock. ```go package repository import ( "github.com/go-nunu/nunu-layout-advanced/internal/model" ) type UserRepository interface { FirstById(id int64) (*model.User, error) } type userRepository struct { *Repository } func NewUserRepository(repository *Repository) *UserRepository { return &UserRepository{ Repository: repository, } } func (r *userRepository) FirstById(id int64) (*model.User, error) { var user model.User if err := r.db.Where("id = ?", id).First(&user).Error; err != nil { return nil, err } return &user, nil } ``` -------------------------------- ### Generate Go Test Coverage Report Source: https://github.com/go-nunu/nunu/blob/main/docs/en/unit_testing.md Commands to generate Go test coverage reports. The first command creates a coverage profile, and the second visualizes it as an HTML file. ```bash go test -coverpkg=./internal/handler,./internal/service,./internal/repository -coverprofile=./coverage.out ./test/server/... go tool cover -html=./coverage.out -o coverage.html ``` -------------------------------- ### Logging a User Event Source: https://github.com/go-nunu/nunu/blob/main/docs/en/guide.md This Go code snippet shows how to log an informational message with user details using the configured logger. ```go package handler import ( "github.com/gin-gonic/gin" "github.com/go-nunu/nunu-layout-basic/internal/service" "github.com/go-nunu/nunu-layout-basic/pkg/helper/resp" "go.uber.org/zap" "net/http" ) // ... func (h *userHandler) GetUserById(ctx *gin.Context) { h.logger.Info("GetUserByID", zap.Any("user", user)) // ... } // ... ``` -------------------------------- ### Compile wire.go Source: https://github.com/go-nunu/nunu/blob/main/README.md Compiles the wire.go file to generate necessary dependency injection code. This is typically used after making changes to dependency configurations. ```bash nunu wire ``` -------------------------------- ### Generate Mock Code with mockgen Source: https://github.com/go-nunu/nunu/blob/main/docs/en/unit_testing.md Use mockgen to generate mock implementations for interfaces. Specify the source file containing the interface and the destination for the generated mock code. ```bash mockgen -source=internal/service/user.go -destination mocks/service/user.go ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.