appctx

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Sep 7, 2023 License: Apache-2.0 Imports: 11 Imported by: 0

README

App-Context

App Context is a library that manages common components such as configurations, database connections, caching, and more.

It simplifies the implementation of new services by abstracting away the complexities of component configurations, allowing developers to focus on building functionality rather than dealing with intricate configuration details.

It was inspired by go-micro and service-context

It provides the following features:

  • Logger component using zerolog.
  • Dynamic management of environment variables and flag variables using viper and it's pflag package (viper supports multiple configuration file formats and reading from remote config systems (etcd or Consul), and watching changes, ...).
  • Ability to output environment variables and flag variables in .env format.
  • Easy integration of additional components as plugins.

Components

  • Server
    • gRPC
    • Gin
  • Client
    • gRPC
  • Pubsub
    • NATS
    • Local
  • Cache
    • Redis
    • Local
  • Storage
    • AWS S3
    • Cloudflare R2
  • Token
    • PASETO
    • JWT
  • Tracer
    • Jaeger
  • Datastore
    • GORM
      • MSSQL
      • MySQL
      • PostgreSQL
      • SQLite
    • Redis
  • Mail

Examples

How to use it

1. Installation:
go get -u github.com/vulcanlabsvn/lib-app-context
2. Define your component:

Your component can be anything but implements this interface:

type Component interface {
	ID() string
	InitFlags()
	Run(AppContext) error
	Stop() error
}

Demo custom component:

package main

import (
	"github.com/spf13/pflag"

	appctx "github.com/vulcanlabsvn/lib-app-context"
)

type demoComponent struct {
	id     string
	data   string
	logger appctx.Logger
}

func NewDemoComponent(id string) *demoComponent {
	return &demoComponent{id: id}
}

func (c *demoComponent) ID() string {
	return c.id
}

func (c *demoComponent) InitFlags() {
	pflag.StringVar(&c.data, "component-data", "demo", "Data string")
}

func (c *demoComponent) Run(ac appctx.AppContext) error {
	c.logger = ac.Logger(c.id)
	return nil
}

func (c *demoComponent) Stop() error {
	return nil
}

func (c *demoComponent) GetData() string {
	return c.data
}

func (c *demoComponent) DoSomething() error {
	c.logger.Print("LOL")
	return nil
}
3. Use the component with App-Context:
package main

import (
	appctx "github.com/vulcanlabsvn/lib-app-context"
)

func main() {
	const cmpId = "abc"
	appCtx := appctx.NewAppContext(
		appctx.WithName("Demo Component"),
		appctx.WithComponent(NewDemoComponent(cmpId)),
	)

	log := appCtx.Logger("service")

	if err := appCtx.Load(); err != nil {
		log.Error(err)
	}

	type CanDoSomething interface {
		GetData() string
		DoSomething() error
	}

	cmp := appCtx.MustGet(cmpId).(CanDoSomething)

	log.Print(cmp.GetData())
	_ = cmp.DoSomething()

	_ = appCtx.Stop()
}
4. Run your code with ENV

Option 1: Command Line

go build -o app
COMPONENT_DATA="Hi There" ./app

Option 2: Environment Variable File (You should do it in a new terminal)

# Create a file named .env with the following content:
COMPONENT_DATA="Hi There"

# Run the application
./app

Option 3: Environment Variable File (with custom name - You should do it in a new terminal)

# Create a file named .env.dev with the following content:
COMPONENT_DATA="Hi There"

# Set the environment variable pointing to the file
ENV_FILE=".env.dev"

# Run the application
./app

You will see this row on your console.

## Case: Only run "./app"
{"level":"debug","prefix":"core.service","time":"2023-06-22T18:18:13+07:00","message":"demo"}

## Case: Use 1 in 3 options above
{"level":"debug","prefix":"core.service","time":"2023-06-22T18:21:35+07:00","message":"Hi There"}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AppContext

type AppContext interface {
	GetPrefix() string
	GetName() string
	GetEnvName() string
	Get(id string) (interface{}, bool)
	MustGet(id string) interface{}
	Load() error
	Stop() error
	Logger(prefix string) Logger
	OutEnv()
}

func NewAppContext

func NewAppContext(opts ...Option) AppContext

type AppLogger

type AppLogger interface {
	GetLogger(prefix string) Logger
}

func GlobalLogger

func GlobalLogger() AppLogger

type Component

type Component interface {
	ID() string
	InitFlags()
	Run(AppContext) error
	Stop() error
}

type Logger

type Logger interface {
	GetLevel() string

	Print(args ...interface{})
	Printf(format string, args ...interface{})

	Debug(args ...interface{})
	Debugf(format string, args ...interface{})

	Info(args ...interface{})
	Infof(format string, args ...interface{})

	Warn(args ...interface{})
	Warnf(format string, args ...interface{})

	Error(err error, args ...interface{})
	Errorf(err error, format string, args ...interface{})

	Fatal(err error, args ...interface{})
	Fatalf(err error, format string, args ...interface{})
}

type Option

type Option func(*appContext)

func WithComponent

func WithComponent(c Component) Option

func WithName

func WithName(name string) Option

func WithPrefix

func WithPrefix(prefix string) Option

Jump to

Keyboard shortcuts

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