Skip to content

Latest commit

 

History

History
240 lines (203 loc) · 6.62 KB

README_En.md

File metadata and controls

240 lines (203 loc) · 6.62 KB

YoyoGo is a simple, light and fast Web framework written in Go.

Release Go GoVersion Report Documentation Contributors License

Features

  • Pretty and fast router
  • Middleware Support
  • Friendly to REST API
  • No regexp or reflect
  • Inspired by many excellent Go Web framework

Installation

go get github.com/yoyofx/yoyogo

Simple Example

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
}

ToDo

Standard

  • Print Logo (YoyoGo)
  • Unified program entry (YoyoGo)
  • Simple router binded handle func
  • HttpContext (request,response)
  • Static File EndPoint(Static File Server)
  • JSON Serialization Struct (Context.M)
  • Get Request File And Save
  • Unite Get Post Data Away (form-data , x-www-form-urlencoded)
  • Binding Model for Http Request ( From, JSON )

Response Render

  • 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

Middleware

  • Logger
  • StaticFile
  • Router
  • Router Middleware
  • CORS
  • JWT
  • Binding

Router

  • GET、POST、HEAD、PUT、DELETE Method Support
  • Router Tree
  • Router Expression
  • RouteData (var)
  • Router Support Struct Refect Func Binded.
  • Router Support Prefix and Group Such as "/api/v1/endpoint"
  • Controller Router And Router Tempalte (Default)
  • Router Filter

Dependency injection

  • Dependency injection Framework
  • Dependency injection Integration
  • Framework's factory and type in Dependency injection Integration

Features

  • configtion
  • WebSocket
  • JWT
  • swagger
  • GRpc
  • Prometheus

Advanced Example

package main
import ...

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

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 router config function
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")
	})

	rb.POST("/info/:id", PostInfo)

	rb.Group("/v1/api", func(rg *router.RouterGroup) {
		rg.GET("/info", GetInfo)
	})

	rb.GET("/info", GetInfo)
	rb.GET("/ioc", GetInfoByIOC)
}

//endregion

//region Http Request Methods
type UserInfo struct {
	UserName string `param:"username"`
	Number   string `param:"q1"`
	Id       string `param:"id"`
}

//HttpGet request: /info  or /v1/api/info
//bind UserInfo for id,q1,username
func GetInfo(ctx *context.HttpContext) {
	ctx.JSON(200,  context.H{"info": "ok"})
}

func GetInfoByIOC(ctx *context.HttpContext) {
	var userAction models.IUserAction
	_ = ctx.RequiredServices.GetService(&userAction)
	ctx.JSON(200,  context.H{"info": "ok " + userAction.Login("zhang")})
}

//HttpPost request: /info/:id ?q1=abc&username=123
func PostInfo(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})
}

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
		}
	}
}

// mvc 
type UserController struct {
	*mvc.ApiController
	userAction models.IUserAction    // IOC
}

// ctor for ioc
func NewUserController(userAction models.IUserAction) *UserController {
	return &UserController{userAction: userAction}
}

// reuqest param binder
type RegiserRequest struct {
	mvc.RequestBody
	UserName string `param:"username"`
	Password string `param:"password"`
}

// auto bind action param by ioc
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() controller.ApiResult {
	return this.OK(this.userAction.Login("zhang"))
}