svc

package
v0.0.0-...-2b7dcb4 Latest Latest
Warning

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

Go to latest
Published: Jan 17, 2024 License: BSD-2-Clause Imports: 18 Imported by: 0

Documentation

Overview

Package svc provides some tooling to make building services with remind101/pkg easier.

Recommend Usage:

	func main() {
		env := svc.InitAll()
		defer env.Close()

		r := httpx.NewRouter()
		// ... add routes

		h := svc.NewStandardHandler(svc.HandlerOpts{
			Router:   r,
			Reporter: env.Reporter,
	})

	s := svc.NewServer(h, svc.WithPort("8080"))
 svc.RunServer(s)
}
Example
package main

import (
	"context"
	"fmt"
	"net/http"
	"time"

	"github.com/remind101/pkg/httpx"
	"github.com/remind101/pkg/svc"
)

func main() {
	env := svc.InitAll()
	defer env.Close()

	r := httpx.NewRouter()
	r.Handle("/hello", httpx.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
		fmt.Fprintln(w, "Hello world!")
		return nil
	}))

	h := svc.NewStandardHandler(svc.HandlerOpts{
		Router:         r,
		Reporter:       env.Reporter,
		HandlerTimeout: 15 * time.Second,
	})

	s := svc.NewServer(h, svc.WithPort("8080"))

	// To illustrate shutting down a background process when server shuts down.
	bg := NewBGProc()
	bg.Start()

	svc.RunServer(s, bg.Stop)
}

type BackgroundProcess struct {
	shutdown chan struct{}
	done     chan struct{}
}

func NewBGProc() *BackgroundProcess {
	return &BackgroundProcess{
		shutdown: make(chan struct{}),
		done:     make(chan struct{}),
	}
}

func (p *BackgroundProcess) Start() {
	go p.start()
}

func (p *BackgroundProcess) start() {
	defer close(p.done)

	t := time.NewTicker(1 * time.Second)
	for {
		select {
		case <-t.C:
			fmt.Println("tick")
		case <-p.shutdown:
			return
		}
	}
}

func (p *BackgroundProcess) Stop() {
	close(p.shutdown)
	<-p.done // Wait for p to finish.
}
Output:

Index

Examples

Constants

This section is empty.

Variables

View Source
var ServerDefaults = func(srv *http.Server) {
	srv.Addr = ":8080"
	srv.WriteTimeout = 5 * time.Second
	srv.ReadHeaderTimeout = 5 * time.Second
	srv.IdleTimeout = 120 * time.Second
}

ServerDefaults specifies default server options to use for RunServer.

Functions

func InitLogger

func InitLogger() logger.Logger

InitLogger configures a leveled logger.

Env Vars: * LOG_LEVEL - The log level

If you want to replace the global default logger:

logger.DefaultLogger = InitLogger()

func InitMetrics

func InitMetrics() func()

InitMetrics configures pkg/metrics

Env Vars: * STATSD_ADDR - The host:port of the statsd server.

func InitReporter

func InitReporter() reporter.Reporter

InitReporter configures and returns a reporter.Reporter instance.

Env Vars: * ROLLBAR_ACCESS_TOKEN - The Rollbar access token * ROLLBAR_ENVIRONMENT - The Rollbar environment (staging, production) * ROLLBAR_ENDPOINT - The Rollbar endpoint: https://api.rollbar.com/api/1/item/

func InitTracer

func InitTracer() func()

InitTracer configures a global datadog tracer.

Env Vars: * DDTRACE_ADDR - The host:port of the local trace agent server. * EMPIRE_APPNAME - App name, used to construct the service name. * EMPIRE_PROCESS - Process name, used to construct the service name.

func NewServer

func NewServer(h http.Handler, opts ...NewServerOpt) *http.Server

NewServer offers some convenience and good defaults for creating an http.Server

func NewStandardHandler

func NewStandardHandler(opts HandlerOpts) http.Handler

NewStandardHandler returns an http.Handler with a standard middleware stack. The last middleware added is the first middleware to handle the request. Order is pretty important as some middleware depends on others having run already.

func RunServer

func RunServer(srv *http.Server, shutdownFuncs ...func())

RunServer handles the biolerplate of starting an http server and handling signals gracefully.

Types

type Env

type Env struct {
	Reporter reporter.Reporter
	Logger   logger.Logger
	Context  context.Context
	Close    func() // Should be called in a defer in main().
}

Env holds global dependencies that need to be initialized in main() and injected as dependencies into an application.

func InitAll

func InitAll() Env

InitAll will initialize all the common dependencies such as metrics, reporting, tracing, and logging.

type HandlerOpts

type HandlerOpts struct {
	Router            *httpx.Router
	Reporter          reporter.Reporter
	ForwardingHeaders []string
	BasicAuth         string
	ErrorHandler      middleware.ErrorHandlerFunc
	HandlerTimeout    time.Duration
}

type NewServerOpt

type NewServerOpt func(*http.Server)

NewServerOpt allows users to customize the http.Server used by RunServer.

func WithPort

func WithPort(port string) NewServerOpt

WithPort sets the port for the server to run on.

Jump to

Keyboard shortcuts

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