go-dandelion Framework

website·Indexed 30 days ago

https://gly-hub.github.io/guide/about.html

A framework scaffolding tool that integrates multiple components including rpcx, fasthttp, gorm, redigo, swagger, and opentracing. It provides a structured directory for RPC and HTTP services, YAML-based configuration, and a dedicated scaffolding tool for rapid application development.

Tokens
6.1K
Snippets
35
Records
44
Agent score
69%

What's inside go-dandelion

  1. Overview of go-dandelion framework capabilities

    go-dandelion is a framework that integrates rpcx, httpfast, gorm, redigo, swagger, and opentracing. It provides built-in functionality for logging, distributed tracing, rate limiting, circuit breaking, service registration, and service discovery. It is designed for rapid development of project structures and components and supports high scalability through customizable plug-ins and business components.
  2. Overview of go-dandelion microservice scaffolding

    go-dandelion is a framework scaffolding tool designed to accelerate the development of Go-based microservices. It automates the creation of the project directory structure and the initialization of commonly used components, reducing boilerplate code and manual setup. Key features include configuration-driven initialization for databases and caches, integrated core functionalities (logging, traceability, rate limiting, circuit breaking, service registration, and discovery), and a customizable middleware/plugin mechanism.
  3. Performance benefits of fasthttp in Gly-Hub

    The HTTP Component utilizes fasthttp instead of the standard Go net/http library to achieve significantly higher performance. Benchmarks indicate that both the fasthttp server and client can be up to 10 times faster than net/http, with substantially lower memory allocations (often 0 B/op and 0 allocs/op in server benchmarks).
  4. Configure MySQL Database connections

    The system currently only supports MySQL. Configuration includes connection pool settings (max open/idle connections), logging levels, and slow query thresholds. It supports a master-slave architecture.
    db:
      dbType: "mysql"
      maxOpenConn: 20
      maxIdleConn: 4
      maxIdleTime: 100
      maxLifeTime: 3600
      level: 4
      slowThreshold: "100ms"
      master:
        user: "root"
        password: "password"
        host: "127.0.0.1"
        port: "3306"
        database: "database"
      slave:
        - user: "root"
          password: "password"
          host: "127.0.0.1"
          port: "3306"
          database: "database"
  5. Contribute to go-dandelion via Pull Requests

    Follow these steps to contribute code changes or bug fixes to the go-dandelion project:

    1. Fork the repository to your own GitHub account.
    2. Clone your forked repository to your local machine for development.
    3. Implement your changes and push them back to your GitHub repository.
    4. Create a 'New pull request' from your repository to the original go-dandelion repository, providing a detailed description of your changes.
  6. Create a new go-dandelion application

    Use the go-dandelion-cli app command to create the main application directory. All services within this application must share the same module and consistent application name.
    # Create application and navigate into it
    go-dandelion-cli app -n go-admin-example && cd go-admin-example
  7. Install the go-dandelion CLI

    Install the go-dandelion CLI tool using the following Go commands to enable faster project structure initialization and component setup.
    go get github.com/gly-hub/go-dandelion/go-dandelion-cli@latest
    go install github.com/gly-hub/go-dandelion/go-dandelion-cli@latest
  8. Start and register an RPCx server

    The RpcServer method in application/rpcserver.go initializes and starts the RPC server using rpcx.NewRPCServer. It configures the server name, address, base path, and registration plugin based on the application configuration.
    func RpcServer(handler interface{}, auth ...rpcx.AuthFunc) {
    	var err error
    	rpcServer, err = rpcx.NewRPCServer(rpcx.ServerConfig{
    		ServerName:      config.Conf.RpcServer.ServerName,
    		Addr:            fmt.Sprintf("%s:%d", addr, config.Conf.RpcServer.Port),
    		BasePath:        config.Conf.RpcServer.BasePath,
    		RegisterPlugin:  rpcx.RegisterPluginType(config.Conf.RpcServer.RegisterPlugin),
    		RegisterServers: config.Conf.RpcServer.RegisterServers,
    		Handle:          handler,
    	})
    	if err != nil {
    		panic(err)
    	}
    	if len(auth) > 0 {
    		rpcServer.RegisterAuthFunc(auth[0])
    	}
    	rpcServer.Start()
    }
  9. Create and register custom HTTP middleware

    Custom middleware is implemented as a function that returns a routing.Handler. The handler receives a *routing.Context. Use c.Next() to pass control to the next handler in the chain, or c.Abort() to stop the request flow. Middleware is registered on a RouteGroup using the .Use() method.
    package middleware
    import (
    	routing "github.com/gly-hub/fasthttp-routing"
    )
    
    func CorsMiddleware() routing.Handler {
    	return func(c *routing.Context) error {
    		c.Response.Header.Set("Access-Control-Allow-Origin", "*")
    		c.Response.Header.Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
    		c.Response.Header.Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
    		c.Response.Header.Set("Access-Control-Max-Age", "86400")
    		c.Response.Header.Set("Access-Control-Allow-Credentials", "true")
    
    		if c.Request.Header.IsOptions() {
    			c.Abort()
    			return nil
    		}
    
    		return c.Next()
    	}
    }
    
    // Registration in route init:
    func InitAuthRoute(baseRouter *routing.RouteGroup) {
    	baseRouter.Use(middleware.CorsMiddleware())
    	authHandler := auth.AuthController{}
    	baseRouter.Post("/login", authHandler.Login)
    }
  10. Customize RPC request headers using RegisterHeaderFunc

    Use the RegisterHeaderFunc interface in application/rpcserver.go to define a custom header handling function. This function allows you to extract parameters from the request context (such as user IDs from HTTP headers) and pass them into the RPC request metadata.
    func setup() {
        // Register header context chain in cmd/api/server.go
        application.RegisterHeaderFunc(HeaderFunc)
    }
    
    func HeaderFunc(ctx *routing.Context, data map[string]string) map[string]string {
        // Extract userId from header and add to metadata
        data["userId"] = ctx.Header.Value("userId")
        return data
    }
  11. Access and use the Gorm database instance

    The framework integrates Gorm and automatically initializes the database based on the configuration file. To interact with the database, use the DB class provided in application/db.go and call the GetDB method to retrieve a *gorm.DB instance.
    package logic
    
    var Test testLogic
    
    type testLogic struct {
    	application.DB
    }
    
    func (a testLogic) Test(){
    	db := a.GetDB()
        // perform database operations
    }
  12. Initialize an RPCx Client

    The rpcx.NewRPCClient function is used to create a new RPC client based on a ClientConfig object. This configuration allows for specifying the client name, base path, plugin registration, server registration, failure retry models, load balancing models, and pool size.
    func initRpcClient() {
        if config.Conf.RpcClient == nil {
            return
        }
        client, err := rpcx.NewRPCClient(rpcx.ClientConfig{
            ClientName:      config.Conf.RpcClient.ClientName,
            BasePath:        config.Conf.RpcClient.BasePath,
            RegisterPlugin:  rpcx.RegisterPluginType(config.Conf.RpcClient.RegisterPlugin),
            RegisterServers: config.Conf.RpcClient.RegisterServers,
            FailRetryModel:  rpcx.FailRetryModel(config.Conf.RpcClient.FailRetryModel),
            BalanceModel:    rpcx.BalanceModel(config.Conf.RpcClient.BalanceModel),
            PoolSize:        config.Conf.RpcClient.PoolSize,
        })
        if err != nil {
            panic(err)
        }
        rpcClient = &RpcClient{
            ClientName: config.Conf.RpcClient.ClientName,
            clientPool: client,
        }
    }