service

package
v1.9.1 Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2024 License: Apache-2.0 Imports: 24 Imported by: 0

Documentation

Overview

Copyright 2023 SpotHero

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Package service provides standard configuration and utilities for a service.

Services contain a cli (cobra.Command), http handlers (mux.Router), a grpc server (grpc.Server), and a metrics interface (prometheus.Registerer).

Example

This is the main entrypoint of the program. Here we create our root command and then execute it.

package main

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

	"github.com/gorilla/mux"
	"github.com/spothero/tools/service"
	"google.golang.org/grpc"
)

type handler struct {
	environment string
}

// RegisterHandlers is a callback used to register HTTP endpoints to the default server
// NOTE: The HTTP server automatically registers /health, /debug, and /metrics -- Have
// a look in your browser!
func (h handler) RegisterHandlers(router *mux.Router) {
	router.HandleFunc("/", h.helloWorld)
}

// RegisterAPIs is a callback used to register GRPC endpoints to the default server.
// The handler is empty since we are not registering any GRPC APIs in this example.
func (h handler) RegisterAPIs(_ *grpc.Server) {
	// Here you would register any GRPC APIs with the GRPC server. In this example we do not have
	// any GRPC endpoints to register.
}

// helloWorld simply writes "hello world" to the caller. It is intended for use as an HTTP callback.
func (h handler) helloWorld(w http.ResponseWriter, _ *http.Request) {
	fmt.Fprintf(w, "Hello World")
}

// This is the main entrypoint of the program. Here we create our root command and then execute it.
func main() {
	// Configure the service with default settings. These settings may be overridden via CLI flags
	// or environment variables from the cobra command
	config := service.Config{
		Name:        "<your-application-name>",
		Version:     "<semantic-version>",
		GitSHA:      "<git-sha>",
		Environment: "<environment>",
	}

	// Using the config, create the cobra command by passing in an HTTP and GRPC registration
	// callback function
	_ = config.ServerCmd(context.Background(), "", "", func(c service.Config) service.HTTPService {
		return handler{environment: c.Environment}
	}, func(c service.Config) service.GRPCService {
		return handler{environment: c.Environment}
	})

	// In the previous function call, we discard the cobra command that is returned. If we had
	// called it `cobraCmd`, we could then run the server by simply calling `Execute()`
	// if err := cobraCmd.Execute(); err != nil {
	//	os.Exit(1)
	// }
}
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	Registry prometheus.Registerer // The Prometheus Registry to use. If nil, the global registry is used by default.
	// A function to be called before starting the service. The context passed into the ServerCmd function will be
	// fed all the way through PreStart and into PostShutdown, enabling communication of state through these functions.
	PreStart      func(ctx context.Context) (context.Context, error)
	PostShutdown  func(ctx context.Context) error // A function to be called before stopping the service
	Name          string                          // Name of the application
	Environment   string                          // Environment where the server is running
	Version       string                          // Semantic Version of the application
	GitSHA        string                          // GitSHA of the application when compiled
	CancelSignals []os.Signal                     // OS Signals to be used to cancel running servers. Defaults to SIGINT/`os.Interrupt`.
}

Config defines service level configuration for HTTP servers

func (Config) CheckFlags

func (c Config) CheckFlags() error

CheckFlags ensures that the Service Config contains all necessary configuration for use at runtime. An error is returned describing any missing fields.

func (*Config) RegisterFlags

func (c *Config) RegisterFlags(flags *pflag.FlagSet)

RegisterFlags registers Service flags with pflags

func (Config) ServerCmd added in v0.18.0

func (c Config) ServerCmd(
	ctx context.Context,
	shortDescription, longDescription string,
	newHTTPService func(Config) HTTPService,
	newGRPCService func(Config) GRPCService,
) *cobra.Command

ServerCmd takes functions, newHTTPService and newGRPCService, that instantiate the GRPCService and HTTPService by consuming the Config object after all values are populated from the CLI and/or environment variables so that values configured by this package are accessible by newService.

Note that this function creates the default server configuration (grpc and http) for use at SpotHero. Consumers of the tools libraries are free to define their own server entrypoints if desired. This function is provided as a convenience function that should satisfy most use cases.

Note that Version and GitSHA *must be specified* before calling this function.

type GRPCService added in v0.16.1

type GRPCService interface {
	RegisterAPIs(*grpc.Server)
}

GRPCService implementors register GRPC APIs with the GRPC server

type HTTPService added in v0.6.0

type HTTPService interface {
	RegisterHandlers(router *mux.Router)
}

HTTPService implementers register HTTP routes with a mux router.

Jump to

Keyboard shortcuts

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