🦄🌈 YoyoGo is a simple, light and fast , dependency injection based micro-service framework written in Go.

Overview

中文 / English

YoyoGo 简单、轻量、快速、基于依赖注入的微服务框架

Release Go GoVersion Report Documentation Contributors License

特色

  • 漂亮又快速的路由器
  • 中间件支持 (handler func & custom middleware)
  • 微服务框架抽象了分层,在一个框架体系兼容各种server实现,如 rest,grpc等
  • 受到许多出色的 Go Web 框架的启发,server可替换,目前实现了 fasthttpnet.http

QQ交流群: 780385870 (Go浪文学院) , 在这里感谢贾国锦帮忙设计的logo很漂亮。

也可以加入我的公众号,通过公众号入群菜单进入微信群

感兴趣的朋友

框架安装

go get github.com/yoyofx/yoyogo

安装依赖 (由于某些原因国内下载不了依赖)

go version < 1.13

window 下在 cmd 中执行:
set GO111MODULE=on
set GOPROXY=https://goproxy.io,direct,https://mirrors.aliyun.com/goproxy/,https://goproxy.cn,https://athens.azurefd.net,https://gonexus.dev 
linux  下执行:
export GO111MODULE=on
export GOPROXY=https://goproxy.cn

go version >= 1.13

go env -w GOPROXY=https://goproxy.io,direct,https://mirrors.aliyun.com/goproxy/,https://goproxy.cn,https://athens.azurefd.net,https://gonexus.dev

vendor

go mod vendor       // 将依赖包拷贝到项目目录中去

简单的例子

package main
import ...

func main() {
	WebApplication.CreateDefaultBuilder(func(rb router.IRouterBuilder) {
        rb.GET("/info",func (ctx *context.HttpContext) {    // 支持Group方式
            ctx.JSON(200, context.H{"info": "ok"})
        })
    }).Build().Run()       //默认端口号 :8080
}

实现进度

标准功能

  • 打印Logo和日志(YoyoGo)
  • 统一程序输入参数和环境变量 (YoyoGo)
  • 简单路由器绑定句柄功能
  • HttpContext 上下文封装(请求,响应)
  • 静态文件端点(静态文件服务器)
  • JSON 序列化结构(Context.H)
  • 获取请求文件并保存
  • 获取请求数据(form-data,x-www-form-urlencoded,Json ,XML,Protobuf 等)
  • Http 请求的绑定模型(Url, From,JSON,XML,Protobuf)

响应渲染功能

  • Render Interface
  • JSON Render
  • JSONP Render
  • Indented Json Render
  • Secure Json Render
  • Ascii Json Render
  • Pure Json Render
  • Binary Data Render
  • TEXT
  • Protobuf
  • MessagePack
  • XML
  • YAML
  • File
  • Image
  • Template
  • Auto formater Render

中间件

  • Logger
  • StaticFile
  • Router Middleware
  • CORS
  • Binding
  • JWT
  • RequestId And Tracker for SkyWorking

路由

  • GET,POST,HEAD,PUT,DELETE 方法支持
  • 路由解析树与表达式支持
  • RouteData路由数据 (/api/:version/) 与 Binding的集成
  • 路由组功能
  • MVC默认模板功能
  • 路由过滤器 Filter

MVC

  • 路由请求触发Controller&Action
  • Action方法参数绑定
  • 内部对象的DI化
  • 关键对象的参数传递

Dependency injection

  • 抽象集成第三方DI框架
  • MVC模式集成
  • 框架级的DI支持功能

扩展

  • 配置
  • WebSocket
  • JWT
  • swagger
  • GRpc
  • Prometheus

进阶范例

package main

import
...

func main() {
	webHost := CreateCustomWebHostBuilder().Build()
	webHost.Run()
}

// 自定义HostBuilder并支持 MVC 和 自动参数绑定功能,简单情况也可以直接使用CreateDefaultBuilder 。
func CreateCustomBuilder() *abstractions.HostBuilder {

	configuration := abstractions.NewConfigurationBuilder().
		AddEnvironment().
		AddYamlFile("config").Build()

	return WebApplication.NewWebHostBuilder().
		UseConfiguration(configuration).
		Configure(func(app *WebApplication.WebApplicationBuilder) {
			app.UseMiddleware(middlewares.NewCORS())
			//WebApplication.UseMiddleware(middlewares.NewRequestTracker())
			app.UseStaticAssets()
			app.UseEndpoints(registerEndpointRouterConfig)
			app.UseMvc(func(builder *mvc.ControllerBuilder) {
				//builder.AddViews(&view.Option{Path: "./static/templates"})
				builder.AddViewsByConfig()
				builder.AddController(contollers.NewUserController)
				builder.AddFilter("/v1/user/info", &contollers.TestActionFilter{})
			})
		}).
		ConfigureServices(func(serviceCollection *dependencyinjection.ServiceCollection) {
			serviceCollection.AddTransientByImplements(models.NewUserAction, new(models.IUserAction))
			//eureka.UseServiceDiscovery(serviceCollection)
			//consul.UseServiceDiscovery(serviceCollection)
			nacos.UseServiceDiscovery(serviceCollection)
		}).
		OnApplicationLifeEvent(getApplicationLifeEvent)
}

//region endpoint 路由绑定函数
func registerEndpoints(rb router.IRouterBuilder) {
	Endpoints.UseHealth(rb)
	Endpoints.UseViz(rb)
	Endpoints.UsePrometheus(rb)
	Endpoints.UsePprof(rb)
	Endpoints.UseJwt(rb)

	rb.GET("/error", func(ctx *context.HttpContext) {
		panic("http get error")
	})

	//POST 请求: /info/:id ?q1=abc&username=123
	rb.POST("/info/:id", func(ctx *context.HttpContext) {
		qs_q1 := ctx.Query("q1")
		pd_name := ctx.Param("username")

		userInfo := &UserInfo{}

		_ = ctx.Bind(userInfo) // 手动绑定请求对象

		strResult := fmt.Sprintf("Name:%s , Q1:%s , bind: %s", pd_name, qs_q1, userInfo)

		ctx.JSON(200, context.H{"info": "hello world", "result": strResult})
	})

	// 路由组功能实现绑定 GET 请求:  /v1/api/info
	rb.Group("/v1/api", func(router *router.RouterGroup) {
		router.GET("/info", func(ctx *context.HttpContext) {
			ctx.JSON(200, context.H{"info": "ok"})
		})
	})

	// GET 请求: HttpContext.RequiredServices获取IOC对象
	rb.GET("/ioc", func(ctx *context.HttpContext) {
		var userAction models.IUserAction
		_ = ctx.RequiredServices.GetService(&userAction)
		ctx.JSON(200, context.H{"info": "ok " + userAction.Login("zhang")})
	})
}

//endregion

//region 请求对象
type UserInfo struct {
	UserName string `param:"username"`
	Number   string `param:"q1"`
	Id       string `param:"id"`
}

// ----------------------------------------- MVC 定义 ------------------------------------------------------

// 定义Controller
type UserController struct {
	*mvc.ApiController
	userAction models.IUserAction // IOC 对象参数
}

// 构造器依赖注入
func NewUserController(userAction models.IUserAction) *UserController {
	return &UserController{userAction: userAction}
}

// 请求对象的参数化绑定
type RegiserRequest struct {
	mvc.RequestBody
	UserName string `param:"username"`
	Password string `param:"password"`
}

// Register函数自动绑定参数
func (this *UserController) Register(ctx *context.HttpContext, request *RegiserRequest) actionresult.IActionResult {
	result := mvc.ApiResult{Success: true, Message: "ok", Data: request}
	return actionresult.Json{Data: result}
}

// use userAction interface by ioc  
func (this *UserController) GetInfo() mvc.ApiResult {
	return this.OK(this.userAction.Login("zhang"))
}

// Web程序的开始与停止事件
func fireApplicationLifeEvent(life *abstractions.ApplicationLife) {
	printDataEvent := func(event abstractions.ApplicationEvent) {
		fmt.Printf("[yoyogo] Topic: %s; Event: %v\n", event.Topic, event.Data)
	}
	for {
		select {
		case ev := <-life.ApplicationStarted:
			go printDataEvent(ev)
		case ev := <-life.ApplicationStopped:
			go printDataEvent(ev)
			break
		}
	}
}
Issues
  • gin框架用了一个模型校验器,考虑一下呗

    gin框架用了一个模型校验器,考虑一下呗

    github.com/go-playground/validator/v10

    opened by icetech233 8
  • 文档中的简单实例无法启动

    文档中的简单实例无法启动

    使用文档中的简单实例代码放到本地执行后,无法正常启动监听端口,没有出现文档中的效果图

    error:panic: runtime error: invalid memory address or nil pointer dereference [signal 0xc0000005 code=0x0 addr=0x20 pc=0x6e2685]

    opened by Artanis-c 2
  • max_request_size 设置后没有起作用

    max_request_size 设置后没有起作用

    设置了 max_request_size 后
    上传 小一点的文件 没问题 , 大一点的文件 就报 body size exceeds the given limit

    bug 
    opened by top3372 2
  • config file at workdir

    config file at workdir

    需要支持在启动参数用指定配置文件目录 (抽象 fie:workdir , remote:adress)

    opened by yoyofx 2
  • Set http response header bugs.

    Set http response header bugs.

    问题: WriteHeader后再 Set Header 是无效的。 需要在Set Hedader后再WriteHeader(statuscode) 这样才能生效。

    opened by yoyofx 1
  • Log for Logrus

    Log for Logrus

    XLog set Logrus

    good first issue 
    opened by yoyofx 1
  • Dev

    Dev

    集成xxl-job

    opened by Artanis-c 1
  • Dev

    Dev

    opened by yoyofx 1
  • Dev

    Dev

    添加分布式锁

    opened by Artanis-c 1
  • Merge pull request #19 from yoyofx/dev

    Merge pull request #19 from yoyofx/dev

    添加ClientFactory

    opened by Artanis-c 1
  • nacos-viper-remote 连接阿里云MSE Nacos 取不回任何内容,也不报错

    nacos-viper-remote 连接阿里云MSE Nacos 取不回任何内容,也不报错

    nacos-viper-remote 连接阿里云MSE Nacos 取不回任何内容,也不报错

    	remote.SetOptions(&remote.Option{
    		Url:         Config.Mse.Server,
    		Port:        uint64(Config.Mse.Port),
    		NamespaceId: Config.Mse.Namespace,
    		GroupName:   Config.Mse.GroupName,
    		Config:      remote.Config{DataId: Config.Mse.ConfigName},
    		Auth:        nil,
    	})
    	remoteConfig := viper.New()
                 // 这里的 endpoint 填 localhost 也一样取不回任何内容
    	err := remoteConfig.AddRemoteProvider("nacos", "mse-8f7b0b60-nacos-ans.mse.aliyuncs.com", "")
    	if err != nil {
    		fmt.Println("加载远程配置失败 :", err.Error())
    	}
    	remoteConfig.SetConfigType("yaml")
    	err = remoteConfig.ReadRemoteConfig()
    	if err != nil {
    		fmt.Println("加载远程配置失败 :", err.Error())
    	}
    	fmt.Println("加载远程配置: Config = ", remoteConfig.GetString("log.level"))
    
    	loadFromViper(remoteConfig)
    
    	fmt.Println("加载远程配置: Config = ", ObjToJSON(Config))
    
    opened by xpsuper 0
  • 日志组件可替换其他实现

    日志组件可替换其他实现

    目前日志用的是第三方日志实现 logrus "github.com/sirupsen/logrus, 希望计划能够抽象日志接口,用户可以通过依赖注入注册自己需要的日志组件。

    opened by whuanle 1
  • 未读取到Nacos配置时报错,而不会使用本地配置

    未读取到Nacos配置时报错,而不会使用本地配置

    在未找到远程配置时,不会读取本地配置文件,而是直接报错,无法启动。

    bug good first issue 
    opened by yoyofx 0
  • 单元测试提供一致性的体验

    单元测试提供一致性的体验

    单元测试中不能使用应用程序中的IOC

    good first issue 
    opened by yoyofx 0
  • 需要HttpContext日志对象

    需要HttpContext日志对象

    在跟请求相关的对象中,应该共用一个 http上下文的日志对象。

    enhancement good first issue 
    opened by yoyofx 0
  • MVC自动绑定运行时错误

    MVC自动绑定运行时错误

    当不给结构果声明 mvc.RequestBody 的 field by index 0 ,会出现绑定不上数据,报错,但看不来是什么样的错误的问题;解决方案是 提示错误,并打印正确日志。

    bug 
    opened by yoyofx 0
  • mvc绑定结构体无报错提示

    mvc绑定结构体无报错提示

    使用web.mvc的 action 方法,自动绑定结构体时,如果绑定如json 类型错误会导致结构体为空,但并没有任何提示

    需要全局打Log。

    bug 
    opened by yoyofx 0
Releases(v1.7.11)
  • v1.7.11(Nov 10, 2021)

  • v1.7.10(Oct 10, 2021)

  • v1.7.9(Sep 18, 2021)

    Features:

    • web context binding for ctx.Bind,add url binding function.
    • add mvc API result builder to build for web response.

    Problems:

    • fixed mvc not found the route, return 404 or error by profile env
    • web context add ctx.bind error tips.
    Source code(tar.gz)
    Source code(zip)
  • v1.7.8(Aug 27, 2021)

  • v1.7.7(Aug 2, 2021)

    Features:

    • Automatic refresh config object on nacos and apollo remote changes.

    Frameworks upgrade:

    • upgrade nacos-viper-remote to v0.4.0

    Contributors:

    • shima-park/agollo ,viper update to v1.8.1 and apollo remote changes event.
    Source code(tar.gz)
    Source code(zip)
  • v1.7.6(Jul 21, 2021)

    Problems:

    • fixed graceful stop and readiness bugs.
    • fixed parallel problem by mvc template, that match it for route path .
    • fixed read remote config hight priority then flags .

    Features:

    • add endpoint /actuator/health/detail, and then output db,redis and more .
    • add endpoint /actuator/routers, and then output all route info list
    Source code(tar.gz)
    Source code(zip)
  • v1.7.5(Jul 14, 2021)

    Framework dependency:

    • New dependency injection framework https://github.com/yoyofxteam/dependencyinjection

    Features:

    • Support grpc connection timeout with context. (fix)
    Source code(tar.gz)
    Source code(zip)
  • v1.7.4(Jul 8, 2021)

    CLI tempates upgrade:

    1. grpc
    2. xxl-job

    Frameworks upgrade:

    1. upgrade gRPC to v1.38.0
    2. upgrade etcd to v3.5.0
    3. upgrade protobuf to v1.5.2
    4. upgrade go-redis to v8.11.0
    5. upgrade go-grpc-middleware to v1.3.0
    6. upgrade gorm to v1.21.11
    7. upgrade logrus to v1.8.1
    8. upgrade go2sky to v1.1.0
    9. upgrade fasthttp v1.28.0
    Source code(tar.gz)
    Source code(zip)
  • v1.7.3(Jul 6, 2021)

    yoyogo cli

    1. yygctl (cli)

    2. templates support , includes console / webapi / mvc / grpc / xxl-job .

    install

    go install github.com/yoyofx/yoyogo/cli/yygctl
    

    local install

    cd yoyogo/cli/yygctl
    go install
    

    Installation location:

    $GOPATH

    add $GOPATH to $PATH Environment variable

    Commands

    There are commands working with application root folder

    new

    yygctl new <TEMPLATE> [-l|--list] [-n <PROJECTNAME>] [-p <TARGETDIR>]
    

    --list

    list all templates

    TEMPLATE LIST

    console / webapi / mvc / grpc / xxl-job

    -n

    generate folder by project name

    -p

    output files to target directory.

    such as

    yygctl new console -n demo -p /Projects
    
    Source code(tar.gz)
    Source code(zip)
  • v1.7.2(Jun 8, 2021)

    1. apollo config center support
    2. changed quick config setting package , github.com/yoyofx/yoyogo/pkg/configuration/{ nacos or apollo }

    examples:

    config := nacosConfig.RemoteConfig("config")
    config := apolloConfig.RemoteConfig("config")
    
    Source code(tar.gz)
    Source code(zip)
  • v1.7.1(May 26, 2021)

  • v1.7.0(May 12, 2021)

  • v1.6.9(May 10, 2021)

  • v1.6.8(Apr 24, 2021)

    1. add grpc hosting and client factory & LB
    2. add host service interface at hosting runing.
    3. add console hosting
    4. service register with self by service discovery
    5. web binding & validator
    Source code(tar.gz)
    Source code(zip)
  • v1.6.7(Apr 13, 2021)

    1. hosting add exeactor service
    2. nacos ,etcd, eureka with service discovery
    3. service discovery client
    4. http client for service discovery
    5. load balancing strategy (random, round_robin)
    Source code(tar.gz)
    Source code(zip)
  • v1.6.6(Apr 6, 2021)

  • v1.6.5(Feb 2, 2021)

  • v1.6.4(Jan 21, 2021)

  • v1.6.3(Jan 15, 2021)

  • v1.6.2(Jan 12, 2021)

  • v1.6.1(Dec 17, 2020)

    Features:

    1. Add web.ApplicationBuilder.SetJsonSerializer for response by json encoder(Camel and Json)
    2. Add object pool for actionresult.Json , that's control object counts for optimization gc .
    3. Add default mvc builder .
    4. Add auto configuration processor for IOC.

    Fixed bugs:

    fixed server.path config bugs. and then restructure server interface.

    Optimization:

    register http and fast server interface by IOC.

    Source code(tar.gz)
    Source code(zip)
  • v1.5.9(Dec 8, 2020)

  • v1.5.7(Nov 26, 2020)

  • v1.5.6(Nov 12, 2020)

  • v1.5.5(Oct 9, 2020)

  • v1.5.4(Sep 2, 2020)

  • v1.5.3(Aug 27, 2020)

    add view engine and DI add CORS and Configuration add email for smtp add server discovery of abstractions. add service register and get instances by Nacos

    Source code(tar.gz)
    Source code(zip)
Owner
YoyoFx
🐳 Go & Java & .NET &Python. I love computer science, system design. @golang @spring-projects @dotnet @kubernetes @python
YoyoFx
Sample full stack micro services application built using the go-Micro framework.

goTemp goTemp is a full stack Golang microservices sample application built using go-micro. The application is built as a series of services that prov

null 48 Jan 8, 2022
NewSQL distributed storage database based on micro service framework

QLite 是基于微服务的 NewSQL 型数据库系统,与传统的一体化数据库不同,该系统将本该内置的多种数据结构(STL)拆分成多个服务模块,每个模块都是独立的一个节点,每个节点都与其主网关进行连接,从而形成分布式存储结构。

null 26 Dec 6, 2021
Micro-service framework in Go

Kite Micro-Service Framework Kite is a framework for developing micro-services in Go. Kite is both the name of the framework and the micro-service tha

Koding, Inc. 3.1k Jan 12, 2022
Another excellent micro service framework

xservice [WIP] Another excellent micro service framework Features RESTful API (base on echo/v4) gRPC & gRPC gateway service & Swagger document generat

新片场 7 Dec 23, 2021
😈 Simple micro-front-end framework.

Development and Maintenance Status RancherOS 1.x is no longer being actively maintained. There are two significant reasons behind this product decisio

Matt D 0 Jan 5, 2022
Automatic Service Mesh and RPC generation for Go micro services, it's a humble alternative to gRPC with Istio.

Mesh RPC MeshRPC provides automatic Service Mesh and RPC generation for Go micro services, it's a humble alternative to gRPC with Istio. In a nutshell

AstraNet Toolkit 68 Nov 18, 2021
White Matrix Micro Service Generate CLI Tool

micro-service-gen-tool White Matrix Micro Service Generate CLI Tool usage templa

null 5 Jan 5, 2022
Micro service frame

MicroFrame MicroFrame是基于go-micro结合go的plugin(需要go1.8或以上)开发的一个微服务框架。 go-micro本身已经做了非常好的抽象和插件化。MicroFrame没有直接采用go-micro,而是在它的基础上重新开发有下面一些原因。 对纯粹的业务开发屏蔽掉掉

never lee 11 Nov 9, 2021
Fastglue is an opinionated, bare bones wrapper that glues together fasthttp and fasthttprouter to act as a micro HTTP framework.

fastglue Overview fastglue is an opinionated, bare bones wrapper that glues together fasthttp and fasthttprouter to act as a micro HTTP framework. It

Zerodha Technology 62 Jan 1, 2022
Go Micro is a framework for distributed systems development

Go Micro Go Micro is a framework for distributed systems development. Overview Go Micro provides the core requirements for distributed systems develop

Asim Aslam 17.5k Jan 15, 2022
a microservice framework for rapid development of micro services in Go with rich eco-system

中文版README Go-Chassis is a microservice framework for rapid development of microservices in Go. it focus on helping developer to deliver cloud native a

null 2.4k Jan 6, 2022
micro-draft-manager is a microservice that helps you to manage unstructured data in your application with sorting and full-text search

micro-draft-manager is a microservice that helps you to manage unstructured data in your application with sorting and full-text search. For example, y

Hamed Abdollahpour 1 Nov 24, 2021
Study Project for the application of micro services and requisition controls

Starting Endpoint GO with Retry Request Install GoLang for Linux Tutorial: LINK

Antenor Pires 3 Dec 29, 2021
A code generator that turns plain old Go services into RPC-enabled (micro)services with robust HTTP APIs.

Frodo is a code generator and runtime library that helps you write RPC-enabled (micro) services and APIs.

Monadic 13 Sep 27, 2021
Micro is a platform for cloud native development

Micro Overview Micro addresses the key requirements for building services in the cloud. It leverages the microservices architecture pattern and provid

Micro 10.8k Jan 15, 2022
goTempM is a full stack Golang microservices sample application built on top of the Micro platform.

goTempM is a full stack Golang microservices sample application built on top of the Micro platform.

null 18 Dec 15, 2021
微服务架构-micro-基于go-zero zrpc etcd 单独集成orm-gorm 日志-uber/zap

micro目录结构 pkg ├── api 业务接口逻辑层 所有的业务逻辑存放目录。 │ ├── model 数据模型 数据管理层,仅用于操作管理数据,如数据库操作 ├── assets

jiwei 7 Dec 31, 2021
A Micro-UTP, plug-able sanity checker for any on-prem JFrog platform instance

hello-frog About this plugin This plugin is a template and a functioning example for a basic JFrog CLI plugin. This README shows the expected structur

rdar 0 Dec 7, 2021
Go micro frame cli tool

go-micro-frame cli tool install git clone [email protected]:jettjia/go-micro-frame-cli.git cd go-micro-frame-cli go build -ldflags "-w -s" -o go-micro-f

jettjia 2 Dec 28, 2021