Example #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)
}
Example #2
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)
	}
}
Example #3
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") == "" {