chassis

package module
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 28, 2023 License: MIT Imports: 19 Imported by: 1

README

chassis

This is a basic microservice chassis that makes it easy to do the default things and possible to do more complex things

HTTP Server

Gin is included as the HTTP server. A standard health/ping route is included by default. The AddRoute() method is the preferred way of adding additional routes. See the example below.

Commandline

Cobra is used for the commands. migrate and serve are included commands with reasonable flags

Logging

Logsrus provides semi-structured logging. Debug output can be triggered with the -D option

Database

Postgres is supported through the sqlx package with migration support through golang-migrate/migrate/v4

Example

package main

import (
	"github.com/alexlovelltroy/chassis"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"github.com/spf13/cobra"
)

type ExampleService struct {
	*chassis.Microservice
}

type ExampleServiceConfig struct {
	chassis.MicroserviceConfig
	parallelism int
}

type Example struct {
	ID   uuid.UUID `json:"id" db:"id"`
	Name string    `json:"name" db:"name"`
}

func (s *ExampleService) CreateExample(c *gin.Context) {
	s.DB.Exec("INSERT INTO example (name) VALUES ($1)", "example")
	c.JSON(200, gin.H{
		"message":    "value",
		"statusCode": "statusCode",
	})
}

func main() {
	cfg := &ExampleServiceConfig{
		MicroserviceConfig: chassis.DefaultMicroserviceConfig(),
		parallelism:        1,
	}
	service := ExampleService{
		Microservice: chassis.NewMicroservice(cfg),
	}
	chassis.ServeCmd.Run = func(cmd *cobra.Command, args []string) {
		service.Init() // Establish connection(s) to external services and configure the gin router
		service.AddRoute("POST", "/example", service.CreateExample)
		service.Serve() // Start the gin router
	}
	chassis.Execute()
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var MigrateCmd = &cobra.Command{
	Use:   "migrate",
	Short: "A brief description of your command",
	Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:

Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
	Run: func(cmd *cobra.Command, args []string) {
		log.Info("migrate called")
		db, err := sql.Open("postgres", cmd.Flags().Lookup("postgres").Value.String())
		if err != nil {
			panic(err)
		}
		defer db.Close()
		level, _ := strconv.Atoi(cmd.Flags().Lookup("target").Value.String())
		err = ApplyMigrationsUp(db, "./migrations/", uint(level))
		if err != nil {
			panic(err)
		}
	},
}

migrateCmd represents the migrate command

View Source
var ServeCmd = &cobra.Command{
	Use:   "serve",
	Short: "Start the http server",
	PreRun: func(cmd *cobra.Command, args []string) {
		log.Debug("Enumerating flags:")
		if cmd.HasFlags() {
			cmd.Flags().VisitAll(func(flag *pflag.Flag) {
				log.Debug(flag.Name, " ", flag.Value)
			})
		}
	},
	Run: func(cmd *cobra.Command, args []string) {

		log.Info("Starting the http server in the chassis")
	},
}

serveCmd represents the serve command

Functions

func ApplyMigrationsUp

func ApplyMigrationsUp(db *sql.DB, migrationPath string, level uint) error

ApplyMigrationsUp applies the database migrations for Postgres Databases up to the latest version

func ConnectDB

func ConnectDB(flavor, uri string) (*sqlx.DB, error)

ConnectDB connects to the database and returns a pointer to the connection object. It is the caller's responsibility to close the connection. The flavor parameter is the name of the database driver to use, e.g. "postgres". The uri parameter is the connection string to use, e.g. "host=localhost port=5432 user=postgres password=postgres dbname=postgres sslmode=disable".

func Execute

func Execute()

Execute adds all child commands to the root command and sets flags appropriately. This is called by main.main(). It only needs to happen once to the rootCmd.

Types

type Config

type Config interface {
	GetPostgresConfig() string
	GetListenAddress() string
}

type Microservice

type Microservice struct {
	ExecutableName string
	InstanceName   string
	InstaceID      uuid.UUID
	Version        string
	Router         *gin.Engine
	DB             *sqlx.DB
	Config         Config
}

func NewMicroservice

func NewMicroservice(config Config) *Microservice

NewMicroservice initializes the bare microservice.

func (*Microservice) AddRoute

func (m *Microservice) AddRoute(method string, path string, handler gin.HandlerFunc)

func (*Microservice) Init

func (m *Microservice) Init()

Init is a convenience function. Developers that want to accept all reasonable defaults can use it to call the other initialization functions in one go.

func (*Microservice) InitPostgres

func (m *Microservice) InitPostgres(config PostgresConfig)

InitPostgres initializes the connection to Postgres

func (*Microservice) InitRouter

func (m *Microservice) InitRouter()

Sets up the Router

func (*Microservice) Serve

func (m *Microservice) Serve()

type MicroserviceConfig

type MicroserviceConfig struct {
	PostgresURI   string
	ListenAddress string
}

func DefaultMicroserviceConfig

func DefaultMicroserviceConfig() MicroserviceConfig

func (*MicroserviceConfig) GetListenAddress

func (c *MicroserviceConfig) GetListenAddress() string

func (*MicroserviceConfig) GetPostgresConfig

func (c *MicroserviceConfig) GetPostgresConfig() string

type PostgresConfig

type PostgresConfig struct {
	ConnectionString      string `mapstructure:"postgres_connection_string"`        // Connection string
	MaxOpenConnections    int    `mapstructure:"postgres_max_open_connections"`     // Maximum number of open connections
	MaxIdleConnections    int    `mapstructure:"postgres_max_idle_connections"`     // Maximum number of idle connections
	ConnectionMaxLifetime int    `mapstructure:"postgres_connection_max_lifetime"`  // Maximum connection lifetime (seconds)
	ConnectionMaxIdleTime int    `mapstructure:"postgres_connection_max_idle_time"` // Maximum connection idle time (seconds)
}

PostgresConfig is a struct that holds the configuration for the Postgres database

var DBConfig PostgresConfig

func DefaultPostgresConfig

func DefaultPostgresConfig() PostgresConfig

Our Sensible defaults are set in code here and can be overridden by instances

func ParsePostgresConfig

func ParsePostgresConfig(config string) PostgresConfig

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL