Exemplo n.º 1
0
func (t *TimedCache) Handle(c context.Context) {
	id := mohttp.RouteID(c) + "." + queryID(c)

	t.mu.Lock()
	if t.caches == nil {
		t.caches = map[string]*timedCacheResp{}
	}

	resp, ok := t.caches[id]
	if !ok {
		t.caches[id] = &timedCacheResp{}
		resp = t.caches[id]
	}

	t.mu.Unlock()

	resp.Lock()
	defer resp.Unlock()

	rw := mohttp.GetResponseWriter(c)

	if time.Since(resp.lastSet) > t.Duration {
		rec := httptest.NewRecorder()
		c = mohttp.WithResponseWriter(c, rec)
		mohttp.Next(c)

		resp.lastSet = time.Now()
		resp.code = rec.Code
		resp.headers = rec.HeaderMap
		resp.body = bytes.NewReader(rec.Body.Bytes())
	}

	copyResp(resp.code, resp.headers, resp.body, rw)
}
Exemplo n.º 2
0
func (a AcceptHandlers) Handle(c context.Context) {
	for mt, h := range a {
		if MatchMediaTypes(c, mt) {
			h.Handle(c)
			mohttp.Next(c)
			return
		}
	}

	mohttp.GetResponseWriter(c).WriteHeader(406)
}
Exemplo n.º 3
0
func (h *ContentLengthHandler) Handle(c context.Context) {
	old := mohttp.GetResponseWriter(c)
	rw := clrw{ResponseWriter: old}

	c = mohttp.WithResponseWriter(c, &rw)
	mohttp.Next(c)

	if rw.useBuf {
		rw.Header().Set("Content-Length", strconv.Itoa(rw.buf.Len()))
		rw.buf.WriteTo(old)
	}
}
Exemplo n.º 4
0
package middleware

import (
	"github.com/NYTimes/gziphandler"
	"github.com/jonasi/mohttp"
	"golang.org/x/net/context"
	"net/http"
	"sync"
)

var GzipHandler mohttp.Handler = mohttp.HandlerFunc(func(c context.Context) {
	h := gziphandler.GzipHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w2 := &addContentTypeWriter{ResponseWriter: w}
		c2 := mohttp.WithResponseWriter(c, w2)

		mohttp.Next(c2)
	}))

	h.ServeHTTP(mohttp.GetResponseWriter(c), mohttp.GetRequest(c))
})

type addContentTypeWriter struct {
	o sync.Once
	http.ResponseWriter
}

func (w *addContentTypeWriter) Write(b []byte) (int, error) {
	w.o.Do(func() {
		h := w.ResponseWriter.Header()

		if h.Get("Content-Type") == "" {
Exemplo n.º 5
0
var JSON = mohttp.DataResponderHandler(&middleware.JSONResponder{
	OnError: func(c context.Context, err error) interface{} {
		return map[string]interface{}{
			"error": err.Error(),
		}
	},

	Transform: func(data interface{}) interface{} {
		return map[string]interface{}{
			"data": data,
		}
	},
})

var AddLinkHeaders = mohttp.HandlerFunc(func(c context.Context) {
	res, ok := hateoas.GetResource(c)

	if ok {
		var (
			rw    = mohttp.GetResponseWriter(c)
			links = res.Links()
		)

		for i := range links {
			rw.Header().Add("Link", links[i].Header())
		}
	}

	mohttp.Next(c)
})
Exemplo n.º 6
0
func (t *templateOptions) Handle(c context.Context) {
	c = templateContextValue.Set(c, t)
	mohttp.Next(c)
}