inssimpleroute

package
v0.10.1 Latest Latest
Warning

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

Go to latest
Published: May 29, 2024 License: Apache-2.0 Imports: 3 Imported by: 0

README

Simple Route Package

This package is designed to provide a simple way to create HTTP routes in your application. It provides a clean and flexible API for integrating into your codebase.

Usage in Apps

package main

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

	"github.com/useinsider/go-pkg/inssimpleroute"
)

// Request type for the use case
type GreetingRequest struct {
	Name string `json:"name"`
}

// Response type for the use case
type GreetingResponse struct {
	Message string `json:"message"`
}

// GreetingUseCase is the core business logic for generating a greeting message
func GreetingUseCase(ctx context.Context, request *GreetingRequest) (*GreetingResponse, error) {
	// Generate a greeting message
	greeting := fmt.Sprintf("Hello, %s!", strings.TrimSpace(request.Name))
	response := &GreetingResponse{
		Message: greeting,
	}
	return response, nil
}

// GreetingRequestDecoder is a custom decoder for GreetingRequest
func GreetingRequestDecoder(_ context.Context, r *http.Request) (*GreetingRequest, error) {
	var request GreetingRequest
	if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
		return nil, err
	}
	return &request, nil
}

func main() {
	// Create a new server route with the GreetingUseCase and a request decoder
	server := inssimpleroute.NewServerWithDefaults(GreetingUseCase, GreetingRequestDecoder)

	// Register the server route
	http.Handle("/greet", server)

	// Start the HTTP server
	port := 8080
	addr := fmt.Sprintf(":%d", port)
	fmt.Printf("Server listening on %s\n", addr)
	err := http.ListenAndServe(addr, nil)
	if err != nil {
		fmt.Printf("Error: %s\n", err)
	}
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultErrorEncoder

func DefaultErrorEncoder(_ context.Context, err error, w http.ResponseWriter)

DefaultErrorEncoder writes the error to the ResponseWriter, by default a content type of text/plain, a body of the plain text of the error, and a status code of 500. If the error implements Headerer, the provided headers will be applied to the response. If the error implements json.Marshaler, and the marshaling succeeds, a content type of application/json and the JSON encoded form of the error will be used. If the error implements StatusCoder, the provided StatusCode will be used instead of 500.

func EncodeJSONResponse

func EncodeJSONResponse[UseCaseResult any](_ context.Context, w http.ResponseWriter, response UseCaseResult) error

EncodeJSONResponse is a EncodeResponseFunc that serializes the response as a JSON object to the ResponseWriter. Many JSON-over-HTTP services can use it as a sensible default. If the response implements Headerer, the provided headers will be applied to the response. If the response implements StatusCoder, the provided StatusCode will be used instead of 200.

Types

type CreateRequestFunc

type CreateRequestFunc func(context.Context, interface{}) (*http.Request, error)

CreateRequestFunc creates an outgoing HTTP request based on the passed request object. It's designed to be used in HTTP clients, for client-side endpoints. It's a more powerful version of EncodeRequestFunc, and can be used if more fine-grained control of the HTTP request is required.

type DecodeRequestFunc

type DecodeRequestFunc[UseCaseCommand any] func(context.Context, *http.Request) (cmd *UseCaseCommand, err error)

DecodeRequestFunc extracts a user-domain request object from an HTTP request object. It's designed to be used in HTTP servers, for server-side endpoints. One straightforward DecodeRequestFunc could be something that JSON decodes from the request body to the concrete request type.

type DecodeResponseFunc

type DecodeResponseFunc func(context.Context, *http.Response) (response interface{}, err error)

DecodeResponseFunc extracts a user-domain response object from an HTTP response object. It's designed to be used in HTTP clients, for client-side endpoints. One straightforward DecodeResponseFunc could be something that JSON decodes from the response body to the concrete response type.

type EncodeRequestFunc

type EncodeRequestFunc func(context.Context, *http.Request, interface{}) error

EncodeRequestFunc encodes the passed request object into the HTTP request object. It's designed to be used in HTTP clients, for client-side endpoints. One straightforward EncodeRequestFunc could be something that JSON encodes the object directly to the request body.

type EncodeResponseFunc

type EncodeResponseFunc[UseCaseResult any] func(context.Context, http.ResponseWriter, UseCaseResult) error

EncodeResponseFunc encodes the passed response object to the HTTP response writer. It's designed to be used in HTTP servers, for server-side endpoints. One straightforward EncodeResponseFunc could be something that JSON encodes the object directly to the response body.

type ErrorEncoder

type ErrorEncoder func(ctx context.Context, err error, w http.ResponseWriter)

ErrorEncoder is responsible for encoding an error to the ResponseWriter. Users are encouraged to use custom ErrorEncoders to encode HTTP errors to their clients, and will likely want to pass and check for their own error types. See the example shipping/handling service.

type Headerer

type Headerer interface {
	Headers() http.Header
}

Headerer is checked by DefaultErrorEncoder. If an error value implements Headerer, the provided headers will be applied to the response writer, after the Content-Type is set.

type SimpleRoute

type SimpleRoute[UseCaseCommand, UseCaseResult any] struct {
	// contains filtered or unexported fields
}

SimpleRoute wraps an endpoint and implements http.HttpHandler.

func NewServer

func NewServer[UseCaseCommand, UseCaseResult any](
	e UseCase[UseCaseCommand, UseCaseResult],
	dec DecodeRequestFunc[UseCaseCommand],
	enc EncodeResponseFunc[UseCaseResult],
	ee ErrorEncoder,
) *SimpleRoute[UseCaseCommand, UseCaseResult]

NewServer constructs a new server, which implements http.HttpHandler and wraps the provided endpoint.

func NewServerWithDefaults

func NewServerWithDefaults[UseCaseCommand, UseCaseResult any](
	e UseCase[UseCaseCommand, UseCaseResult],
	dec DecodeRequestFunc[UseCaseCommand],
) *SimpleRoute[UseCaseCommand, UseCaseResult]

NewServerWithDefaults constructs a new server, which implements http.HttpHandler and wraps the provided endpoint.

func (*SimpleRoute[UseCaseCommand, UseCaseResult]) ServeHTTP

func (sr *SimpleRoute[UseCaseCommand, UseCaseResult]) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.HttpHandler.

type StatusCoder

type StatusCoder interface {
	StatusCode() int
}

StatusCoder is checked by DefaultErrorEncoder. If an error value implements StatusCoder, the StatusCode will be used when encoding the error. By default, StatusInternalServerError (500) is used.

type UseCase

type UseCase[UseCaseCommand, UseCaseResult any] func(ctx context.Context, cmd *UseCaseCommand) (rs UseCaseResult, err error)

Jump to

Keyboard shortcuts

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