Example #1
0
func (j *JSONResponder) HandleResult(c context.Context, data interface{}) error {
	if j.Transform != nil {
		data = j.Transform(data)
	}

	mohttp.GetResponseWriter(c).Header().Add("Content-Type", "application/json")
	return json.NewEncoder(mohttp.GetResponseWriter(c)).Encode(data)
}
Example #2
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 #3
0
func (r *DetectTypeResponder) HandleResult(c context.Context, res interface{}) error {
	var (
		rw = mohttp.GetResponseWriter(c)
		rd io.Reader
	)

	if b, ok := res.([]byte); ok {
		rd = bytes.NewReader(b)
	} else if b, ok := res.(BytesProvider); ok {
		rd = bytes.NewReader(b.Bytes())
	} else if r, ok := res.(io.Reader); ok {
		rd = r
	} else {
		return errors.New("DataProvider result cannot be coerced into []byte")
	}

	_, err := io.Copy(&onFirstWriteWriter{
		Writer: rw,
		OnFirstWrite: func(b []byte) {
			ct := http.DetectContentType(b)
			rw.Header().Set("Content-Type", ct)
		},
	}, rd)
	return err
}
Example #4
0
func (t *TextResponder) HandleErr(c context.Context, err error) {
	if t.OnError != nil {
		t.OnError(c, err)
		return
	}

	mohttp.GetResponseWriter(c).WriteHeader(500)
}
Example #5
0
func (r *DetectTypeResponder) HandleErr(c context.Context, err error) {
	if r.OnError != nil {
		r.OnError(c, err)
		return
	}

	mohttp.GetResponseWriter(c).WriteHeader(500)
}
Example #6
0
func TemplateHandler(fn func(c context.Context) (string, map[string]interface{})) mohttp.Handler {
	return mohttp.HandlerFunc(func(c context.Context) {
		var (
			name, data = fn(c)
			t          = templateContextValue.Get(c).(*templateOptions)
		)
		t.template.ExecuteTemplate(mohttp.GetResponseWriter(c), name, data)
	})
}
Example #7
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)
}
Example #8
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 #9
0
func (j *JSONResponder) HandleErr(c context.Context, err error) {
	if h, ok := err.(mohttp.HTTPError); ok {
		mohttp.GetResponseWriter(c).WriteHeader(int(h))
	}

	if j.OnError != nil {
		data := j.OnError(c, err)
		err = j.HandleResult(c, data)
	}

	if err != nil {
		panic("No error json handler specified - error: " + err.Error())
	}
}
Example #10
0
func (t *TextResponder) HandleResult(c context.Context, res interface{}) error {
	rw := mohttp.GetResponseWriter(c)
	rw.Header().Set("Content-Type", "text/plain")

	if str, ok := res.(string); ok {
		rw.Write([]byte(str))
		return nil
	}

	if str, ok := res.(Stringer); ok {
		rw.Write([]byte(str.String()))
		return nil
	}

	return errors.New("DataProvider result cannot be coerced into string")
}
Example #11
0
func (r *BytesResponder) HandleResult(c context.Context, res interface{}) error {
	rw := mohttp.GetResponseWriter(c)
	rw.Header().Set("Content-Type", "application/octet-stream")

	if b, ok := res.([]byte); ok {
		rw.Write(b)
		return nil
	}

	if b, ok := res.(BytesProvider); ok {
		rw.Write(b.Bytes())
		return nil
	}

	return errors.New("DataProvider result cannot be coerced into []byte")
}
Example #12
0
func EtagHandlerFunc(fn func(context.Context) (interface{}, string, error)) mohttp.Handler {
	return mohttp.DataHandlerFunc(func(c context.Context) (interface{}, error) {
		d, etag, err := fn(c)

		if err != nil {
			return nil, err
		}

		var (
			found = mohttp.GetRequest(c).Header.Get("If-None-Match")
			rw    = mohttp.GetResponseWriter(c)
		)

		rw.Header().Set("ETag", etag)

		if etag == found {
			rw.WriteHeader(304)
			return mohttp.DataNoBody, nil
		}

		return d, nil
	})
}
Example #13
0
	"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") == "" {
			h.Set("Content-Type", http.DetectContentType(b))
		}
Example #14
0
func FileHandler(fn func(context.Context) string) mohttp.Handler {
	return mohttp.HandlerFunc(func(c context.Context) {
		path := fn(c)
		http.ServeFile(mohttp.GetResponseWriter(c), mohttp.GetRequest(c), path)
	})
}
Example #15
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)
})
Example #16
0
)

var version = hateoas.NewResource(
	hateoas.Path("/version"),
	hateoas.GET(mohttp.StaticDataHandler(Version)),
)

var status = hateoas.NewResource(
	hateoas.Path("/status"),
	hateoas.PATCH(mohttp.HandlerFunc(func(c context.Context) {
		var body struct {
			Status string `json:"status"`
		}

		if err := middleware.JSONBodyDecode(c, &body); err != nil {
			mohttp.GetResponseWriter(c).WriteHeader(500)
			return
		}

		if body.Status == "inactive" {
			getServer(c).Close()
		}
	})),
)

var plugins = hateoas.NewResource(
	hateoas.Path("/plugins"),
	hateoas.GET(mohttp.DataHandlerFunc(func(c context.Context) (interface{}, error) {
		var (
			plugins = getServer(c).plugins
			resp    = make([]pl, len(plugins))