service

package module
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Mar 7, 2024 License: MIT Imports: 5 Imported by: 0

README

service

License go.mod Go version GoDoc Latest tag Go Report

Golang library that handle the complexity of running long-living goroutines (like a http server).

func main() {
    ctx := context.Background()

	listener1, err := net.Listen("tcp", ":8080")
	if err != nil {
		panic(fmt.Errorf("unable to create listener: %v", err))
	}

	server1 := netservice.Serve(
		&http.Server{Handler: http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
			rw.WriteHeader(http.StatusTeapot)
		})},
		listener1,
		netservice.ServerWithServeErrorTransformer(func(err error) error {
			if errors.Is(err, http.ErrServerClosed) {
				return nil
			}
			return err
		}),
	)

	listener2, err := netservice.NewListener(ctx, ":9090")
	if err != nil {
		panic(fmt.Errorf("unable to create listener: %v", err))
	}

	server2 := netservice.Serve(
		&http.Server{Handler: http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
			rw.WriteHeader(http.StatusOK)
		})},
		listener2,
		netservice.ServerWithServeErrorTransformer(func(err error) error {
			if errors.Is(err, http.ErrServerClosed) {
				return nil
			}
			return err
		}),
	)

	if err := service.Run(ctx, server1, server2); err != nil {
		panic(fmt.Errorf("unable to run services: %v", err))
	}
}

License

This project is under the MIT licence, please see the LICENSE file.

Documentation

Index

Constants

View Source
const ErrUnexpectedReturn sentinelError = "unexpected return"

ErrUnexpectedReturn is triggered if a runner is not expected to return but returned.

Variables

This section is empty.

Functions

func Run

func Run(ctx context.Context, runner Runner, runners ...Runner) error

Run starts all runners and blocks until all runners returned. Runners are expected to stop only due to context cancellation reasons. This mean that context.Canceled on runners is not considered an error.

Run returns an error if:

  • a runner returned unexpectedly (with or without error) ; in that case ErrUnexpectedReturn is returned
  • after being stopped, a runner returned an error that is not context.Canceled

Types

type RunFunc

type RunFunc func(ctx context.Context) error

RunFunc type is an adapter to allow the use of functions as Runner. RunFunc(f) is a Runner that calls f as Run() function.

func (RunFunc) Run

func (f RunFunc) Run(ctx context.Context) error

Run implements Runner.

type Runner

type Runner interface {
	Run(ctx context.Context) error
}

Runner defines how runners are handled.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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