background

package module
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Feb 26, 2024 License: MIT Imports: 8 Imported by: 0

README

background

Convert go handler to background job

package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/adzeitor/background"
	"github.com/adzeitor/background/services/inmemory"
)

func slowHandler(w http.ResponseWriter, _ *http.Request) {
	for i := 0; i < 10; i++ {
		time.Sleep(time.Second * 1)
	}
	log.Println("Completed")
	w.Write([]byte("Completed"))
}

func allJobsHandler(service *inmemory.Service) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		job, err := service.Jobs()
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		json.NewEncoder(w).Encode(job)
	}
}

func main() {
	logger := log.New(os.Stdout, "jobs:", log.LstdFlags)
	service := inmemory.New()
	bg := background.NewMiddleware(service, logger)

	asyncSlowHandler := bg.InBackground(http.HandlerFunc(slowHandler), "SLOW_HANDLER")
	http.Handle("/slow", asyncSlowHandler)

	http.Handle("/jobs", allJobsHandler(service))

	fmt.Println("to create background job use http://localhost:3000/slow")
	fmt.Println("to track jobs use http://localhost:3000/jobs")
	log.Fatal(http.ListenAndServe(":3000", nil))
}

Documentation

Index

Constants

View Source
const (
	StatusWorking   = Status("WORKING")
	StatusCompleted = Status("COMPLETED")
)

List of available statuses of background jobs.

Variables

This section is empty.

Functions

func WithNoCancelContext added in v0.1.2

func WithNoCancelContext(ctx context.Context) context.Context

Types

type Background

type Background struct {
	Service      JobService
	Logger       Logger
	PingInterval time.Duration
	// contains filtered or unexported fields
}

Background converts handlers to background handlers.

func NewMiddleware

func NewMiddleware(service JobService, logger Logger) *Background

NewMiddleware creates new middleware that use service as backend for job information updating. Currently all handlers executed in goroutines.

func (*Background) InBackground

func (bg *Background) InBackground(
	origHandler http.Handler,
	kind string,
) http.Handler

InBackground converts handler to background handler. It respond immediately with job ID that can be used to track status and getting response.

type Job

type Job struct {
	ID        string    `json:"id"`
	Status    Status    `json:"status"`
	Response  *Response `json:"response"`
	Kind      string    `json:"kind"`
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
}

Job represents background job.

type JobService

type JobService interface {
	JobStarted(ctx context.Context, kind string) (Job, error)
	JobCompleted(ctx context.Context, id string, response Response) error
	Ping(ctx context.Context, id string) error
}

JobService manages background jobs information.

type Logger

type Logger interface {
	Println(...interface{})
}

Logger manages logging.

type Response

type Response struct {
	StatusCode int
	Header     http.Header
	Body       string
}

Response represents response of origin handler which runs in background.

type Status

type Status string

Status represents status of background job.

Directories

Path Synopsis
services

Jump to

Keyboard shortcuts

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