Beispiel #1
0
// BeforeAction logs request and response data and times the handler
// h's execution.
func BeforeAction(h func(http.ResponseWriter, *http.Request), contentType string) func(http.ResponseWriter, *http.Request) {

	return func(rw http.ResponseWriter, req *http.Request) {
		defer logs.TimerEnd(logs.TimerBegin(fmt.Sprintf("%s '%s'", req.Method, req.URL.Path)))

		// log request headers
		logs.Log(fmt.Sprintf("Request headers: %s", req.Header))

		// parse params
		err := req.ParseForm()
		if logs.CheckErr(err) {
			http.Error(rw, err.Error(), http.StatusInternalServerError)
			return
		}

		// new recorder for logging/middleware
		rec := httptest.NewRecorder()
		// set content-type
		if contentType != "" {
			rec.Header().Set("Content-Type", contentType)
		}

		h(rec, req)

		// log response
		logs.Log(fmt.Sprintf("Response status: %d", rec.Code))
		logs.Log(fmt.Sprintf("Response headers: %s", rec.Header()))

		// copy to actual ResponseWriter
		copyResponse(rw, rec)
	}
}
Beispiel #2
0
// JSON marshal's the response variable into json and prints it on rw.
func JSON(rw http.ResponseWriter, response interface{}) {

	encoded, err := json.Marshal(response)
	if logs.CheckErr(err) {
		http.Error(rw, err.Error(), http.StatusInternalServerError)
		return
	}
	fmt.Fprint(rw, string(encoded))
}
Beispiel #3
0
// GET /crawl
// Crawls a given url
func Crawl(rw http.ResponseWriter, req *http.Request) {

	uStr := req.Form.Get("url")
	if uStr == "" {
		http.Error(rw, "Missing url parameter", 422)
		return
	}

	u, err := crawler.Parse(uStr)
	if logs.CheckErr(err) {
		http.Error(rw, err.Error(), 422)
		return
	}

	JSON(rw, crawler.Crawl(u))
}