controller

package module
v0.0.0-...-e87d193 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2024 License: ISC Imports: 8 Imported by: 0

README

controller

This package is aimed to reduce amount of boilerplate code when writing regular http.Handle. It provides simple and explicit API to define HTTP endpoints.

To install controller:

go get -u github.com/andriiyaremenko/controller

How to use:
package main

import (
	"net/http"

	"github.com/go-chi/chi/v5"
	"github.com/andriiyaremenko/controller"
)

// type definitions and other code..

func main() {
	r := chi.NewRouter()
	handle := func(r *http.Request) (ResponseModel, error) {
		service := SomeService(r.Context())
		result, err := service.Do()

		if err != nil {
			return result, err
		}

		return result, nil
	}

	r.Post(
		"/", controller.
			Respond[ResponseModel](handle).
			With(controller.SuccessCode(http.StatusCreated)),
	)

	http.ListenAndServe(":3000", r)
}

Documentation

Overview

This package is aimed to reduce amount of boilerplate code when writing regular http.Handle. It provides simple and explicit API to define HTTP endpoints.

To install controller:

go get -u github.com/andriiyaremenko/controller

How to use: package main

import (

"net/http"

"github.com/go-chi/chi/v5"
"github.com/andriiyaremenko/controller"

)

// type definitions and other code..

func main() {
	r := chi.NewRouter()
	handle := func(r *http.Request) (ResponseModel, error) {
		service := SomeService(r.Context())
		result, err := service.Do()

		if err != nil {
			return result, err
		}

		return result, nil
	}

	r.Post(
		"/", controller.
			Respond[ResponseModel](handle).
			With(controller.SuccessCode(http.StatusCreated)),
	)

	http.ListenAndServe(":3000", r)
}

```

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ErrorHandle

func ErrorHandle(matcher ErrorMatcher) func(Options)

ErrorHandle checks if error is of E type and returns designated HTTP Status Code with transformed response using as callback if true.

func ErrorWithCode

func ErrorWithCode[E any](httpCode int) func(Options)

ErrorWithCode checks if error is of E type and returns designated HTTP Status Code with E instance as a response if true.

func ReadJSON

func ReadJSON[T any](req *http.Request) (*T, error)

Request reader to read JSON from Body.

func ResponseWriter

func ResponseWriter(w WriteResponse) func(Options)

Sets response writer.

func SetDefaultErrorHandlers

func SetDefaultErrorHandlers(handlers ...ErrorMatcher)

func SetLogger

func SetLogger(l Logger)

func SuccessCode

func SuccessCode(code int) func(Options)

Sets success response HTTP Status Code.

Types

type DecoratedResponse

type DecoratedResponse[T, U any] func(U) Respond[T]

func (DecoratedResponse[T, U]) With

func (decorated DecoratedResponse[T, U]) With(opts ...func(Options)) func(U) http.Handler

type ErrorMatcher

type ErrorMatcher interface {
	Match(*http.Request, error) (any, int)
}

type Logger

type Logger interface {
	Error(msg string, args ...any)
}

type MatchError

type MatchError func(error) (any, int)

func (MatchError) Match

func (match MatchError) Match(_ *http.Request, err error) (any, int)

type MatchErrorRequest

type MatchErrorRequest func(*http.Request, error) (any, int)

MatchErrorRequest transforms error to HTTP status code and response body.

func (MatchErrorRequest) Match

func (match MatchErrorRequest) Match(r *http.Request, err error) (any, int)

type Options

type Options interface {
	SuccessCode(int)
	ErrorHandlers(...ErrorMatcher)
	WriteResponse(WriteResponse)
}

type ReadRequestError

type ReadRequestError struct {
	// contains filtered or unexported fields
}

If request payload reading failed - ReadRequestError is returned.

func (*ReadRequestError) Error

func (err *ReadRequestError) Error() string

func (*ReadRequestError) Unwrap

func (err *ReadRequestError) Unwrap() error

type RecoveredError

type RecoveredError struct {
	Panic any
	Stack []byte
}

func (*RecoveredError) Error

func (err *RecoveredError) Error() string

func (*RecoveredError) Unwrap

func (err *RecoveredError) Unwrap() error

type Respond

type Respond[T any] func(*http.Request) (T, error)

Respond is http.Handler that utilizes generics to process request payload and reduce amount of boilerplate code.

func (Respond[T]) ServeHTTP

func (handle Respond[T]) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (Respond[T]) With

func (handle Respond[T]) With(opts ...func(Options)) http.Handler

With allows change default Respond behaviour with options.

type WriteResponse

type WriteResponse interface {
	Write(*http.Request, http.ResponseWriter, any, int)
	WriteError(*http.Request, http.ResponseWriter, any, int)
}

type WriteResponseFn

type WriteResponseFn func(*http.Request, http.ResponseWriter, any, int)

Response writer type.

var WriteJSON WriteResponseFn = func(_ *http.Request, w http.ResponseWriter, data any, status int) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.WriteHeader(status)

	if data == nil {
		return
	}

	if err := json.NewEncoder(w).Encode(data); err != nil {
		logger().Error("failed to write JSON", "error", err)
	}
}

Response writer to write JSON response in body with Content-Type "application/json; charset=utf-8" Header.

func (WriteResponseFn) Write

func (fn WriteResponseFn) Write(r *http.Request, w http.ResponseWriter, value any, code int)

func (WriteResponseFn) WriteError

func (fn WriteResponseFn) WriteError(r *http.Request, w http.ResponseWriter, err any, code int)

Jump to

Keyboard shortcuts

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