gin

package
v2.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 3, 2022 License: Apache-2.0 Imports: 11 Imported by: 0

Documentation

Overview

Package gin defines a set of basic building blocks for instrumenting KrakenD gateways built using the gin router

Example (Backend)
ctx := context.Background()
buf := bytes.NewBuffer(make([]byte, 1024))
l, _ := logging.NewLogger("DEBUG", buf, "")

metricProducer := New(ctx, defaultCfg, l)

bf := metricProducer.BackendFactory("backend_layer", proxy.CustomHTTPProxyFactory(client.NewHTTPClient))

p := bf(&config.Backend{URLPattern: "/some/{url}", Decoder: encoding.JSONDecoder})

ts1 := httptest.NewServer(http.HandlerFunc(dummyHTTPHandler))
defer ts1.Close()

parsedURL, _ := url.Parse(ts1.URL)
req := proxy.Request{URL: parsedURL, Method: "GET", Body: ioutil.NopCloser(strings.NewReader(""))}
for i := 0; i < 10; i++ {
	resp, err := p(ctx, &req)
	if err != nil {
		fmt.Println("Error:", err)
	}
	if !resp.IsComplete {
		fmt.Println("Unexpected response:", *resp)
	}
}

engine := gin.New()
engine.GET("/stats", metricProducer.NewExpHandler())
w := httptest.NewRecorder()
reqHTTP, err := http.NewRequest("GET", "/stats", ioutil.NopCloser(strings.NewReader("")))
if err != nil {
	fmt.Println(err)
}
engine.ServeHTTP(w, reqHTTP)
resp := w.Result()
data, _ := ioutil.ReadAll(resp.Body)
resp.Body.Close()

if len(data) < 5000 {
	fmt.Println("unexpected response size:", len(data), string(data))
}
// Uncomment to see what's been logged
// fmt.Println(buf.String())

// Uncomment the next line and remove the # to see the stats report as the test fails
// fmt.Println(string(data))
// #Output: golly
Output:

Example (Proxy)
ctx := context.Background()
buf := bytes.NewBuffer(make([]byte, 1024))
l, _ := logging.NewLogger("DEBUG", buf, "")
cfg := &config.EndpointConfig{
	Endpoint: "/test/endpoint",
}

metricProducer := New(ctx, defaultCfg, l)

response := proxy.Response{Data: map[string]interface{}{}, IsComplete: true}
fakeFactory := proxy.FactoryFunc(func(_ *config.EndpointConfig) (proxy.Proxy, error) {
	return func(_ context.Context, _ *proxy.Request) (*proxy.Response, error) { return &response, nil }, nil
})
pf := metricProducer.ProxyFactory("proxy_layer", fakeFactory)

p, err := pf.New(cfg)
if err != nil {
	fmt.Println("Error:", err)
}
req := proxy.Request{}
for i := 0; i < 10; i++ {
	resp, err := p(ctx, &req)
	if err != nil {
		fmt.Println("Error:", err)
	}
	if resp != &response {
		fmt.Println("Unexpected response:", *resp)
	}
}

engine := gin.New()
engine.GET("/stats", metricProducer.NewExpHandler())
w := httptest.NewRecorder()
reqHTTP, err := http.NewRequest("GET", "/stats", ioutil.NopCloser(strings.NewReader("")))
if err != nil {
	fmt.Println(err)
}
engine.ServeHTTP(w, reqHTTP)
resp := w.Result()
data, _ := ioutil.ReadAll(resp.Body)
resp.Body.Close()

if len(data) < 5000 {
	fmt.Println("unexpected response size:", len(data), string(data))
}

// Uncomment to see what's been logged
// fmt.Println(buf.String())

// Uncomment the next line and remove the # to see the stats report as the test fails
// fmt.Println(string(data))
// #Output: golly
Output:

Example (Router)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
buf := bytes.NewBuffer(make([]byte, 1024))
l, _ := logging.NewLogger("DEBUG", buf, "")

metricProducer := New(ctx, defaultCfg, l)

engine := gin.New()
hf := metricProducer.NewHTTPHandlerFactory(func(_ *config.EndpointConfig, _ proxy.Proxy) gin.HandlerFunc {
	return gin.WrapF(dummyHTTPHandler)
})
engine.GET("/test", hf(&config.EndpointConfig{Endpoint: "/some/{url}"}, proxy.NoopProxy))
engine.GET("/stats", metricProducer.NewExpHandler())

for i := 0; i < 10; i++ {
	w := httptest.NewRecorder()
	req, err := http.NewRequest("GET", "/test", ioutil.NopCloser(strings.NewReader("")))
	if err != nil {
		fmt.Println(err)
	}
	engine.ServeHTTP(w, req)
	resp := w.Result()
	if resp.Header.Get("x-test") != "ok" {
		fmt.Println("unexpected header:", resp.Header.Get("x-test"))
	}
	if resp.StatusCode != 200 {
		fmt.Println("unexpected status code:", resp.StatusCode)
	}
}
metricProducer.Router.Aggregate()

w := httptest.NewRecorder()
req, err := http.NewRequest("GET", "/stats", ioutil.NopCloser(strings.NewReader("")))
if err != nil {
	fmt.Println(err)
}
engine.ServeHTTP(w, req)
resp := w.Result()
data, _ := ioutil.ReadAll(resp.Body)
resp.Body.Close()

if len(data) < 5000 {
	fmt.Println("unexpected response size:", len(data), string(data))
}

// Uncomment to see what's been logged
// fmt.Println(buf.String())

// Uncomment the next line and remove the # to see the stats report as the test fails
// fmt.Println(string(data))
// #Output: golly
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewHTTPHandlerFactory

NewHTTPHandlerFactory wraps a handler factory adding some simple instrumentation to the generated handlers

Types

type Metrics

type Metrics struct {
	*metrics.Metrics
}

Metrics is the component that manages all the metrics for the gin-based gateways

func New

New creates a new metrics producer with support for the gin router

func (*Metrics) NewEngine

func (m *Metrics) NewEngine() *gin.Engine

NewEngine returns a *gin.Engine with some defaults and the stats endpoint (no logger)

func (*Metrics) NewExpHandler

func (m *Metrics) NewExpHandler() gin.HandlerFunc

NewExpHandler creates an http.Handler ready to expose all the collected metrics as a JSON

func (*Metrics) NewHTTPHandlerFactory

func (m *Metrics) NewHTTPHandlerFactory(hf krakendgin.HandlerFactory) krakendgin.HandlerFactory

NewHTTPHandlerFactory wraps a handler factory adding some simple instrumentation to the generated handlers

func (*Metrics) RunEndpoint

func (m *Metrics) RunEndpoint(ctx context.Context, e *gin.Engine, l logging.Logger)

RunEndpoint runs the *gin.Engine (that should have the stats endpoint) with the logger

Jump to

Keyboard shortcuts

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