kcd

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Sep 15, 2022 License: Apache-2.0 Imports: 10 Imported by: 4

README ¶

kcd logo

kcd is passing lint and tests Coverage Status documentation


comparaison between a code with and without kcd

🌠 KCD

KCD is a grandiose REST helper that wrap your shiny handler into a classic http handler. It manages all you want for building REST services.

This library is opinionated by default but customizable which mean it uses some other libraries like Chi, Logrus... KCD is modular so each pieces of the code that rely on a specific library can be changed.

💪 Example

🚀 QuickStart

package main

import (
	"fmt"
	"net/http"

	"github.com/go-chi/chi"
	"github.com/go-chi/chi/middleware"

	"github.com/alexisvisco/kcd"
)

func main() {
	r := chi.NewRouter()
	r.Use(middleware.RequestID)

	// You can configure kcd with kcd.Config

	r.Get("/{name}", kcd.Handler(YourHttpHandler, http.StatusOK))
	//                       ^ Here the magic happen this is the only thing you need
	//                         to do. Adding kcd.Handler(your handler)
	_ = http.ListenAndServe(":3000", r)
}

// CreateCustomerInput is an example of input for an http request.
type CreateCustomerInput struct {
	Name     string   `path:"name"`                 // you can extract value from: 'path', 'query', 'header', 'ctx'
	Emails   []string `query:"emails" exploder:","` // exploder split value with the characters specified
	Subject  string   `json:"body"`                 // it also works with json body
}

// CreateCustomerOutput is the output type of the http request.
type CreateCustomerOutput struct {
	Name string `json:"name"`
}

// YourHttpHandler is your http handler but in a shiny version.
// You can add *http.ResponseWriter or http.Request in params if you want.
func YourHttpHandler(in *CreateCustomerInput) (CreateCustomerOutput, error) {
	// do some stuff here
	fmt.Printf("%+v", in)

	return CreateCustomerOutput{Name: in.Name}, nil
}

Install

go get github.com/alexisvisco/kcd@v0.1.0

Compatibility with framework

☕ Benefits

  • More readable code
  • Focus on what it matters: business code
  • No more code duplication with unmarshalling, verifying, validating, marshalling ...
  • You could have one interface for the client and server implementation

📖 Read more...

Documentation ¶

Index ¶

Constants ¶

This section is empty.

Variables ¶

View Source
var Config = Configuration{
	StringsExtractors: []extractor.Strings{extractor.Path{}, extractor.Header{}, extractor.Query{}},
	ValueExtractors:   []extractor.Value{extractor.Context{}},

	ErrorHook:    hook.Error,
	RenderHook:   hook.Render,
	BindHook:     hook.Bind(256 * 1024),
	ValidateHook: hook.Validate,
	LogHook:      hook.Log,
}

Config is the instance of Configuration type. You can add as many extractor you want, modify them ... You can set your custom hook too.

View Source
var ErrStopHandler = errors.New("KCD_STOP_HANDLER")

ErrStopHandler will stop execution of the handler, a blank response will be sent

Functions ¶

func Handler ¶

func Handler(h interface{}, defaultStatusCode int) http.HandlerFunc

Handler returns a default http handler.

The handler may use the following signature:

 func(
			[ctx context.Context],
			[response http.ResponseWriter],
			[request *http.Request],
			[INPUT object ptr]) ([OUTPUT object], error)

INPUT and OUTPUT struct are both optional. As such, the minimal accepted signature is:

func() error

There is an exception because you can also use default http handler but the status code, and the render hook will not be used.

A complete example for an INPUT struct:

 type CreateCustomerInput struct {
		Name          string            `path:"name"`                 // /some-path/{name}
		Authorization string            `header:"X-authorization"`    // header name 'X-authorization'
		Emails        []string          `query:"emails" exploder:","` // /some-path/{name}?emails=a@1.fr,b@1.fr
     Body          map[string]string `json:"body"`                 // json body with {body: {a: "hey", b: "hoy"}}

		ContextualID *struct {
			ID string `ctx:"id" default:"robot"` // ctx value with key 'id' or it will default set ID to "robot"
		}
	}

The wrapped handler will bind the parameters from the query-string, path, body and headers, context, and handle the errors.

Handler will panic if the kcd handler or its input/output values are of incompatible type.

Types ¶

type Configuration ¶

type Configuration struct {
	StringsExtractors []extractor.Strings
	ValueExtractors   []extractor.Value

	ErrorHook    hook.ErrorHook
	BindHook     hook.BindHook
	ValidateHook hook.ValidateHook
	RenderHook   hook.RenderHook
	LogHook      hook.LogHook

	Verbose bool
}

Configuration is the main configuration type of kcd.

Jump to

Keyboard shortcuts

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