GithubHelp home page GithubHelp logo

go-nunu / nunu Goto Github PK

View Code? Open in Web Editor NEW
1.7K 13.0 115.0 3.73 MB

A CLI tool for building Go applications.

Home Page: https://go-nunu.github.io/nunu/

License: MIT License

Go 91.21% Smarty 7.64% Makefile 1.14%
golang-cli go golang scaffold ddd gin

nunu's Introduction

Nunu — A CLI tool for building Go applications.

Nunu is a scaffolding tool for building Go applications. Its name comes from a game character in League of Legends, a little boy riding on the shoulders of a Yeti. Just like Nunu, this project stands on the shoulders of giants, as it is built upon a combination of popular libraries from the Go ecosystem. This combination allows you to quickly build efficient and reliable applications.

🚀Tips: This project is very complete, so updates will not be very frequent, welcome to use.

Nunu

Documentation

Features

Key Features

  • Low Learning Curve and Customization: Nunu encapsulates popular libraries that Gophers are familiar with, allowing you to easily customize the application to meet specific requirements.
  • High Performance and Scalability: Nunu aims to be high-performance and scalable. It uses the latest technologies and best practices to ensure that your application can handle high traffic and large amounts of data.
  • Security and Reliability: Nunu uses stable and reliable third-party libraries to ensure the security and reliability of your application.
  • Modular and Extensible: Nunu is designed to be modular and extensible. You can easily add new features and functionality by using third-party libraries or writing your own modules.
  • Complete Documentation and Testing: Nunu has comprehensive documentation and testing. It provides extensive documentation and examples to help you get started quickly. It also includes a test suite to ensure that your application works as expected.

Concise Layered Architecture

Nunu adopts a classic layered architecture. In order to achieve modularity and decoupling, it uses the dependency injection framework Wire.

Nunu Layout

Nunu CLI

Nunu

Directory Structure

.
├── 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

The project architecture follows a typical layered structure, consisting of the following modules:

  • cmd: This module contains the entry points of the application, which perform different operations based on different commands, such as starting the server or executing database migrations. Each sub-module has a main.go file as the entry file, as well as wire.go and wire_gen.go files for dependency injection.

  • config: This module contains the configuration files for the application, providing different configurations for different environments, such as development and production.

  • deploy: This module is used for deploying the application and includes deployment scripts and configuration files.

  • internal: This module is the core module of the application and contains the implementation of various business logic.

    • handler: This sub-module contains the handlers for handling HTTP requests, responsible for receiving requests and invoking the corresponding services for processing.

    • job: This sub-module contains the logic for background tasks.

    • model: This sub-module contains the definition of data models.

    • repository: This sub-module contains the implementation of the data access layer, responsible for interacting with the database.

    • server: This sub-module contains the implementation of the HTTP server.

    • service: This sub-module contains the implementation of the business logic, responsible for handling specific business operations.

  • pkg: This module contains some common utilities and functions.

  • scripts: This module contains some script files used for project build, test, and deployment operations.

  • storage: This module is used for storing files or other static resources.

  • test: This module contains the unit tests for various modules, organized into sub-directories based on modules.

  • web: This module contains the frontend-related files, such as HTML, CSS, and JavaScript.

In addition, there are some other files and directories, such as license files, build files, and README. Overall, the project architecture is clear, with clear responsibilities for each module, making it easy to understand and maintain.

Requirements

To use Nunu, you need to have the following software installed on your system:

  • Go 1.19 or higher
  • Git
  • Docker (optional)
  • MySQL 5.7 or higher (optional)
  • Redis (optional)

Installation

You can install Nunu with the following command:

go install github.com/go-nunu/nunu@latest

Tips: If go install succeeds but the nunu command is not recognized, it is because the environment variable is not configured. You can add the GOBIN directory to the environment variable.

Create a New Project

You can create a new Go project with the following command:

nunu new projectName

By default, it pulls from the GitHub source, but you can also use an accelerated repository in China:

// Use the basic template
nunu new projectName -r https://gitee.com/go-nunu/nunu-layout-basic.git
// Use the advanced template
nunu new projectName -r https://gitee.com/go-nunu/nunu-layout-advanced.git

This command will create a directory named projectName and generate an elegant Go project structure within it.

Create Components

You can create handlers, services, repositories, and models for your project using the following commands:

nunu create handler user
nunu create service user
nunu create repository user
nunu create model user

or

nunu create all user

These commands will create components named UserHandler, UserService, UserRepository, and UserModel, respectively, and place them in the correct directories.

Run the Project

You can quickly run the project with the following command:

nunu run

This command will start your Go project and support hot-reloading when files are updated.

Compile wire.go

You can quickly compile wire.go with the following command:

nunu wire

This command will compile your wire.go file and generate the required dependencies.

Contribution

If you find any issues or have any improvement suggestions, please feel free to raise an issue or submit a pull request. Your contributions are highly appreciated!

License

Nunu is released under the MIT License. For more information, see the LICENSE file.

Star History

Star History Chart

nunu's People

Contributors

ch3nnn avatar codingcn avatar elisongomes avatar infezek avatar silver-brother avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nunu's Issues

undefined: newApp

➜ k8s_deploy git:(main) ✗ go build cmd/server/main.go

command-line-arguments

cmd/server/main.go:15:23: undefined: newApp

go build error

需要一个demo的使用指导

我研究了一下这个脚手架,发现根本不知道怎么用,文档指引是站在很熟悉框架的角度写的,只指导了一个项目怎么启动起来,但是没有给出指引我要怎么加入自己的东西,比如我想加入一个模型,应该做什么?我试了按照user的方式加入了一个新模型,但是搞了半天不知道怎么更新数据库的表。然后同理,怎么添加接口。。。
希望知道文档能够提供一个demo来说明这些步骤

windows 上每次更新文件都会弹出防火墙警告

如题,每次都点允许很烦,而且防火墙允许的应用会多出非常多无用选项
image

我查了下需要在启动端口前面加上127.0.0.1。如果说本地开发调试我感觉这样会好一点,":%d"在部署的时候用

http.Run(servers.ServerHTTP, fmt.Sprintf(":%d", conf.GetInt("http.port")))
改成
http.Run(servers.ServerHTTP, fmt.Sprintf("127.0.0.1:%d", conf.GetInt("http.port")))

还有种方案就是添加入站规则方向项目运行的端口。

你有啥想法和建议?

在创建模型或者仓库时自动处理带下划线的单词

eg:

nunu create repository user_log

new name for Create Struct

// internal/command/create.go
var (
		modelName string
	)
	if strings.Contains(c.FileName, "_") {
		for _, v := range strings.Split(c.FileName, "_") {
			modelName += strings.ToUpper(v[0:1]) + v[1:]
		}
		c.ModelName = modelName
	}

expected result

截屏2024-03-01 14 03 59

服务启动环境变量

请教一下,默认启动是debug,比如测试环境需要切换test,命令如何执行?(本地执行和docker执行分别是怎样的),另外是不是要额外创建一个test.yml作为配置文件?

关于Web Framework的替换

可否把内置的Web Framework变成可以替换的,比如Gin可以替换为Fiber适用于高性能场景?

zap日志链路追踪问题

请问gorm sql日志看代码通过zapgorm2配置到zap上,但实际打印出来sql日志没有请求trace用来追踪,怎么解决?

更新频率问题

作者大大,你这个框架之后最近更新变化会很大吗?

教程中服务handle注册问题

func NewServerHTTP(
// ...
orderHandler *handler.OrderHandler, // new ============>>>> 不能是引用类型,否则,下面无法调用方法
) *gin.Engine {
// ...

// 无权限路由
noAuthRouter := r.Group("/").Use(middleware.RequestLogMiddleware(logger))
{
	noAuthRouter.GET("/order", orderHandler.GetOrderById)   // new

框架有监控,链路追踪的技术方案吗?

框架跟同类相比,非常不错!
不过看了文档,没有监控,链路追踪的方案。
监控,链路追踪是发现线上问题很重要的一环,本框架有技术方案可以提供吗?

error: 修改config/local.yml的MySQL 数据库连接, 然后使用 nunu run ,报错, 只有使用 go run ./cmd/server -conf=config/prod.yml 才能正确启动

我在使用 [nunu-layout-advanced]模板后,修改了 conf/local.yml, conf/prod.yml 的 MySQL 数据库连接, 并修改了 internal/repository/repository.go:30

	db, err := gorm.Open(mysql.Open(conf.GetString("data.mysql.nunu")), &gorm.Config{})// 使用我自己创建数据库

随后使用 nunu run 命令启动 报错:

 D:/LeetCode/Golang/Go-Web/github.com/formal-you/nunu-hello/internal/repository/repository.go:30
[error] failed to initialize database, got error dial tcp 127.0.0.1:3306: connectex: No connection could be made because the 
target machine actively refused it.
panic: dial tcp 127.0.0.1:3306: connectex: No connection could be made because the target machine actively refused it.

goroutine 1 [running]:
github.com/formal-you/nunu-hello/internal/repository.NewDB(0x0?)
        D:/LeetCode/Golang/Go-Web/github.com/formal-you/nunu-hello/internal/repository/repository.go:32 +0x134        
main.newApp(0xc00005ff20?, 0xc00000a100)
        D:/LeetCode/Golang/Go-Web/github.com/formal-you/nunu-hello/cmd/server/wire_gen.go:28 +0x1b5
main.main()
        D:/LeetCode/Golang/Go-Web/github.com/formal-you/nunu-hello/cmd/server/main.go:16 +0x5c
exit status 2

但当我改为使用 go run ./cmd/server -conf=config/prod.yml

D:\LeetCode\Golang\Go-Web\github.com\formal-you\nunu-hello>go run ./cmd/server -conf=config/prod.yml
load conf file: config/prod.yml
{"level":"info","ts":1693402524.6552145,"caller":"server/main.go:20","msg":"server start","host":"http://172.27.32.1:8000"}  

能够正常启动, conf/local.yml, conf/prod.yml 我都同步修改了MySQL 数据库连接. 按说 使用 go run ./cmd/server -conf=config/local.yml 不会报错, 但同样会报上面的错误.

新增加一个model后如何自动在数据库中创建相应的表?

通过nunu create model role 后成功创建role的model,修改完role对应的属性后,如何在数据库中创建相应的表?

我当前的做法是在/internal/server/migration.go 文件中修改Start 方法:

func (m *Migrate) Start(ctx context.Context) error {
	if err := m.db.AutoMigrate(&model.User{}); err != nil {
		m.log.Error("user migrate error", zap.Error(err))
		return err
	}
	if err := m.db.AutoMigrate(&model.Role{}); err != nil {
		m.log.Error("role migrate error", zap.Error(err))
		return err
	}
	if err := m.db.AutoMigrate(&model.Device{}); err != nil {
		m.log.Error("role migrate error", zap.Error(err))
		return err
	}
	m.log.Info("AutoMigrate success")
	os.Exit(0)
	return nil
}

然后在/cmd/migration目录执行nunu run 命令。

虽然这种做法实现了所述问题,但是对代码入侵比较大,有没有什么自动的方式来实现此功能?

Project Roadmap

Is there a roadmap for what you plan to add to the project?
It would be good to have a discussion group; I am interested in being a contributor to the project.

postgresql数据库支持

目前只看到了对mysql的支持,如果需要支持postgresql,需要修改什么地方呢?

新版的接口错误处理问题

func HandleError(ctx *gin.Context, httpCode int, err error, data interface{}) { if data == nil { data = map[string]string{} } resp := Response{Code: ErrorCodeMap[err], Message: err.Error(), Data: data} ctx.JSON(httpCode, resp) }
这里这个code,如果在service层里的错误是未定义的会返回0吧,虽然外层已经有http错误码区分,但是0还是和success有所冲突吧,
而且Message是否应该把这种未知错误统一返回内部错误,在api里隐藏具体的错误信息呢,只在日志里记录是否会比较好

build and run error

nunu run :
package demo/cmd/server
imports demo/pkg/config: build constraints exclude all Go files in x:\work\code\go\demo\pkg\config

go build :
package demo/cmd/server
imports demo/pkg/config: build constraints exclude all Go files in x:\work\code\go\demo\pkg\config

runtime: go 1.20

nunu create all xxx 创建了dao 文件

nunu 版本:

1.0.4

现象:

已经使用 nunu upgrade 提示是最新版。
使用nunu new $project 创建出来的项目是没有dao 文件夹,有一个repository 文件夹,但是nunu create all xxx创建的还是dao的文件夹.

安裝

windows安裝好以后,nunu new 失败:无法将“nunu”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后再试一次。

关于 gorm gen

在该项目中是否会考虑引入gorm.io/gen模块来生成更加友好的数据库模型

日志用起来感觉有些繁琐

建议提供全局的日志,如果我需要在工具类里打印日志要么不用次整合包的统一日志,要么手动传递,有点太繁琐

关于gorm logger

现在的模板log内的zap实例,具有和gorm的接口logger同名的方法,但是参数不同,导致现在无法实现gorm自定义log,不知道是不是我的方法有问题

关于手动打包的问题

我没有看到nunu有手动打包项目的命令,还是目前项目只支持镜像打包。是不是直接build /cmd文件夹下对应服务的main文件就可以

nunu wire

nunu wire 不能改变 wire_gen.go 文件。
make file 文件添加 cd cmd/server && wire 可以

如果要连接多个数据库,该怎么写呢?

image
比如增加一个order数据库,repository.go增加:
func NewOrderDB(conf *viper.Viper) *gorm.DB { dbOrder, err := gorm.Open(mysql.Open(conf.GetString("data.mysql.order")), &gorm.Config{}) if err != nil { panic(fmt.Sprintf("mysql error: %s", err.Error())) } return dbOrder }

wire.go增加如下:
image
然后执行nunu wire all 报错:
image

测试文件调用路由的问题

image
image

在新建了一个menusHandler的情况下。user_test 的setupRouter 里面 在使用到NewServerHTTP()的时候 也需要传入menusHandler。
我应该怎么改进它呢?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.