Skip to content

go-st/kapusta

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

18 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Kapusta

Build Status

It`s middleware approach for using http.Client. You can wrap your client with different functionality:

  • log every request
  • append auth headers
  • use http cache
  • use etcd for service discovery
  • and whatever you want!

Just like a cabbage!

Client interface

Internal http package doesn`t have any interface for http clients, so Kapusta provides very simple client interface:

type IClient interface {
	Do(*http.Request) (*http.Response, error)
}

http.Client supports it out of box.

Decorators

Decorator is like a middleware:

type DecoratorFunc func(IClient) IClient

Kapusta provides some helpful decorators for you:

  • HeadersDecorator(values map[string]string) Adds headers to requests
  • HeaderDecorator(name, value string) Like headers, but add only one header.
  • RecoverDecorator() Converts all panics into errors
  • BaseURLDecorator(baseURL string) Replaces scheme and host to baseURL value.

Usage

client := http.DefaultClient

decoratedClient := kapusta.Decorate(
    client,
    decorator.HeaderDecorator("X-Auth", "123"),
    decorator.RecoverDecorator(), // better to place it last to recover panics from decorators too
)

Create your own decorator

There are two ways of creating new decorators.

You can create some new struct:

struct AwesomeStuffClient {
    client kapusta.Client
}

func(c *AwesomeStuffClient) Do(r *http.Request) (*http.Response, error) {
    // some stuff before call
    res, err := c.client.Do(r)
    // some stuff after call
    
    return res, err
}

func AwesomeStuffDecorator(c kapusta.IClient) kapusta.IClient {
    return &AwesomeStuffClient{client: c}
}

Or you can create just a function with type:

type ClientFunc func(*http.Request) (*http.Response, error)

So the same example will be looks like:

func AwesomeStuffDecorator(c kapusta.IClient) kapusta.IClient {
	return kapusta.ClientFunc(func(r *http.Request) (*http.Response, error) {
		// some stuff before call
        res, err := c.client.Do(r)
        // some stuff after call
        
        return res, err
	})
}

Sometimes it`s required to pass some params in decorator, for details see Headers decorator.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages