services

package
v0.0.0-...-8aa6e6d Latest Latest
Warning

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

Go to latest
Published: Sep 1, 2024 License: MIT Imports: 7 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	DefaultAddress             = "127.0.0.1:9000"
	DefaultGracefulStopEnabled = true
	DefaultGracefulStopTimeout = time.Second * 5
)
View Source
var DefaultProfilerURIPrefix = "/debug/pprof/"

Functions

func DefaultServerFactory

func DefaultServerFactory(config HTTPServerConfig, handlers []Handler, muxers ...Muxer) *http.Server

Returns default *net/http.Server.

func NewMuxer

func NewMuxer(uri string, handlers []Handler, muxers ...Muxer) *http.ServeMux

Returns a muxer with applied handlers and children muxers.

func PprofMuxer

func PprofMuxer(prefix string) *http.ServeMux

Returns a net/http.ServeMux with pprof handlers registered.

Types

type HTTPServer

type HTTPServer struct {
	// Server configuration
	Config HTTPServerConfig

	// A list of handlers that are including in the root muxer.
	// A Config.BaseURL will be used as prefix for that handlers.
	Handlers []Handler

	// A list of children muxers that root muxer will include.
	Muxers []Muxer

	// A factory to return a *net/http.Server instance.
	// If nil, the DefaultServerFactory will be used.
	ServerFactory ServerFactory

	// Whether to stop server gracefully or not.
	GracefulStopEnabled bool

	// If graceful stop is enabled, this timeout will be used
	// to wait until its stop. If timeout has reached,
	// server exits immediately.
	GracefulStopTimeout time.Duration

	// Whether to enable pprof muxer or not.
	PprofEnabled bool

	// If pprof is enabled, this URI will be used.
	PprofURIPrefix string
	// contains filtered or unexported fields
}

An http server that implements appetizer.Servicer interface. Allows to predefine HTTP handlers and a list of muxers to include.

Example
package main

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

	"github.com/homier/appetizer"
	"github.com/homier/appetizer/services"
)

func main() {
	app := appetizer.App{
		Name: "ExampleHTTPServer",
		Services: []appetizer.Service{{
			Name: "http_server",
			Servicer: &services.HTTPServer{
				Handlers: []services.Handler{{
					Path: "GET /hello",
					Handler: func(w http.ResponseWriter, _ *http.Request) {
						if _, err := io.WriteString(w, "world\n"); err != nil {
							panic(err)
						}
					},
				}},
				PprofEnabled: true,
			},
		}},
	}

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	go func() {
		if err := app.Run(ctx); err != nil {
			app.Log().Fatal().Err(err).Msg("Fatal error while running an application")
		}
	}()

	<-app.WaitCh()

	resp, err := http.Get("http://" + services.DefaultAddress + "/hello")
	if err != nil {
		app.Log().Fatal().Err(err).Msg("Could not query test HTTP server")
	}

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		app.Log().Fatal().Err(err).
			Msg("Could not read response body from test HTTP server endpoint")
	}

	fmt.Println(string(body))
}
Output:

world

func (*HTTPServer) Init

func (hs *HTTPServer) Init(log log.Logger) error

Initializes HTTPServer instance. Building of a *net/http.Server instance happens here.

func (*HTTPServer) Run

func (hs *HTTPServer) Run(ctx context.Context) error

Runs the configured server in background and waits until its exit or the context cancellation. Returns either a server error, or a context error, or a server stop error.

type HTTPServerConfig

type HTTPServerConfig struct {
	Address string `json:"address" default:"127.0.0.1:9000"`
	BaseURL string `json:"base_url" default:"/"`

	ReadTimeout       time.Duration `json:"read_timeout" default:"0s"`
	ReadHeaderTimeout time.Duration `json:"read_header_timeout" default:"1s"`
	WriteTimeout      time.Duration `json:"write_timeout" default:"0s"`
	IdleTimeout       time.Duration `json:"idle_timeout" default:"0s"`

	MaxHeaderBytes int `json:"max_header_bytes" default:"0"`

	// If enabled, you must configure TLS for server by yourself using
	// a ServerFactory function
	TLSEnabled bool `json:"tls_enabled" default:"false"`
}

High level server configuration. See net/http.Server for more.

type Handler

type Handler struct {
	Path    string
	Handler http.HandlerFunc
}

A type for defining a pair of net/http.HandlerFunc and its URI path.

type Muxer

type Muxer = http.Handler

An alias for net/http.Handler interface.

type ServerFactory

type ServerFactory func(config HTTPServerConfig, handlers []Handler, muxers ...Muxer) *http.Server

Function type used as *net/http.Server factory.

Jump to

Keyboard shortcuts

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