nilgo

package module
Version: v0.0.0-...-c7eb554 Latest Latest
Warning

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

Go to latest
Published: Aug 26, 2021 License: MIT Imports: 15 Imported by: 0

README

nilgo 🐃 GoDoc Go Report Card Build Codecov Go stability-wip

Nilgo provides an out-of-the-box, cloud-native, production-ready, minimalist Go application framework with pre-customized configuration, log, and telemetry for major Cloud providers.

Nilgo is Nilgai in brezhoneg. The nilgai (literally meaning "blue cow") is the largest Asian antelope and is ubiquitous across the northern Indian subcontinent.

Installation

go get github.com/ktong/nilgo

Quick Start

It's usually used in main function to bootstrap the application. Below code runs gRPC server on Google Cloud Platform.

package main

import (
  "google.golang.org/grpc"

  "github.com/ktong/nilgo"
  "github.com/ktong/nilgo/gcp"
  ngrpc "github.com/ktong/nilgo/grpc"
)

func main() {
  nilgo.Run(
    nilgo.WithOptions(
      gcp.Options(
        gcp.WithProfiler(),
        gcp.WithTrace(),
        gcp.WithMetric(),
        gcp.WithRuntimeMetric(),
      )...,
    ),
  )(
    func(ctx context.Context) error {
      // initialize your gRPC server implementation here.
      // It should use defer for resources clean up.
      
      return ngrpc.NewServer(
        ngrpc.WithTelemetry(),
      )(
        func(srv *grpc.Server) {
          // Register your gRPC server implementation here.
        },
      )(ctx)
    },
  )
}

Benchmark

Implementation principles

Don't Panic

Nilgo encourages explicit error handling instead of implicit panic, so all code has a determined execution path. Conversely, nilgo also does not recover any panic from dependencies unless it clearly understand how to handle it.

Every Goroutine Matters

Nilgo guarantees every single goroutine shutdown gracefully. It leverages goleak detecting goroutine leaking.

Functional Options Pattern with Currying

Functional options pattern provides a handy and friendly way to handle options. Nilgo sometimes uses currying with options if it needs two variadic arguments. See nilgo.Run for a sample.

Documentation

Overview

Package nilgo provides logger, config, telemetry and more for application runs on Cloud with service mesh.

It's usually used in main() function to bootstrap the application. For example:

func main() {
    nilgo.Run(options...)(runners...)
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Run

func Run(opts ...Option) func(...run.Runner)

Run runs app synchronously with provided options.

The running can be interrupted if any runner returns non-nil error, or it receives an os.Signal specified via WithSignals. It waits all runners return unless it's forcefully killed by os.

It panics on first non-nil error (if any) received. It does not recover panic, which causes running crashes if any panic happens without recovery in runner.

Example
package main

import (
	"context"
	"fmt"

	"github.com/ktong/nilgo"
)

func main() {
	nilgo.Run()(
		func(context.Context) error {
			fmt.Println("Job has been run.")

			return nil
		},
	)

}
Output:

Job has been run.

func TestMain

func TestMain(opts ...Option) func(*testing.M, ...run.Runner)

TestMain can be used in a TestMain function for package tests to ensure that their dependencies have been initialized properly. To use it, your TestMain function should look like:

func TestMain(m *testing.M) {
  nilgo.TestMain(nilgo.WithGoLeak())(m, fixtures, and, runners)
}

See https://golang.org/pkg/testing/#hdr-Main for more details.

To wait the test subject ready, it delays tests running for 1 second, which would be good for most cases. You may use run.WithDelay to wait extra duration or run.WithGate to notify the subject's readiness.

Types

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option configures how we run the application.

func WithGoLeak

func WithGoLeak(opts ...goleak.Option) Option

WithGoLeak returns an Option that enables Goroutine leaks detector.

func WithOptions

func WithOptions(opts ...interface{}) Option

WithOptions returns an Option that provides options for underlie capability. For now, it only can be one of following:

- log.Option
- config.Option
- run.Runner
- func(context.Context) error

The interface{} for opts would be switched to type interface as soon as generic is released.

Example
package main

import (
	"context"
	"embed"
	"flag"

	"github.com/ktong/nilgo"
	"github.com/ktong/nilgo/config"
	"github.com/ktong/nilgo/log"
	"go.uber.org/goleak"
	"go.uber.org/zap"
)

//go:embed testdata
var cfg embed.FS

func main() {
	_ = flag.Set("config.file", "testdata/config.yaml")
	defer func() {
		_ = flag.Set("config.file", "config/config.yaml")
	}()

	nilgo.Run(
		nilgo.WithOptions(
			config.WithFS(cfg),
			log.WithZapLogger(zap.NewExample()),
		),
		nilgo.WithGoLeak(goleak.IgnoreCurrent()),
	)(
		func(ctx context.Context) error {
			var user string
			if err := config.Unmarshal("app.user", &user); err != nil {
				return err
			}

			log.Ctx(ctx).Info("example log", "user", user)

			return nil
		},
	)

}
Output:

{"level":"info","msg":"example log","user":"cfg"}

func WithSignals

func WithSignals(signal os.Signal, signals ...os.Signal) Option

WithSignals returns an Option that specifies one or more os.Signal which could terminate the running.

The default signals are syscall.SIGINT and syscall.SIGTERM.

Example
package main

import (
	"context"
	"os"
	"syscall"

	"github.com/ktong/nilgo"
	"github.com/ktong/nilgo/run"
)

func main() {
	nilgo.Run(
		nilgo.WithSignals(syscall.SIGQUIT),
	)(
		blockRunner(),
		func(context.Context) error {
			return syscall.Kill(os.Getpid(), syscall.SIGQUIT)
		},
	)

}

func blockRunner() run.Runner {
	return func(ctx context.Context) error {
		c := make(chan struct{})

		return run.WithCloser(
			func(context.Context) error {
				<-c

				return nil
			},
			func() error {
				close(c)

				return nil
			},
		)(ctx)
	}
}
Output:

Directories

Path Synopsis
Package codec provides codes to marshal/unmarshal struct to byte sequence.
Package codec provides codes to marshal/unmarshal struct to byte sequence.
Package config provides an application configuration system.
Package config provides an application configuration system.
Package gcp provides customization for Google Cloud Platform.
Package gcp provides customization for Google Cloud Platform.
Package grpc provides opinionated production-ready configured gRPC server.
Package grpc provides opinionated production-ready configured gRPC server.
Package http provides opinionated production-ready configured HTTP server.
Package http provides opinionated production-ready configured HTTP server.
Package log provides a minimalist logging API.
Package log provides a minimalist logging API.
Package run runs a group of functions finitely or infinitely.
Package run runs a group of functions finitely or infinitely.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto
y or Y : Canonical URL