예제 #1
0
// Wraps the provided handler function encapsulating boilerplate code so handlers do not have to
// implement it themselves: parsing a request's form, formatting a proper JSON response, emitting
// the request stats, etc.
func MakeHandler(app *App, fn HandlerFunc, spec Spec) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if err := parseForm(r); err != nil {
			ReplyInternalError(w, fmt.Sprintf("Failed to parse request form: %v", err))
			return
		}

		start := time.Now()
		response, err := fn(w, r, mux.Vars(r))
		elapsedTime := time.Since(start)

		var status int
		if err != nil {
			response, status = responseAndStatusFor(err)
		} else {
			status = http.StatusOK
		}

		logInfo := spec.Logger
		if logInfo == nil {
			logInfo = log.Infof
		}
		logInfo("Request(Status=%v, Method=%v, Path=%v, Form=%v, Time=%v, Error=%v)",
			status, r.Method, r.URL, r.Form, elapsedTime, err)

		app.stats.TrackRequest(spec.MetricName, status, elapsedTime)

		Reply(w, response, status)
	}
}
예제 #2
0
// GetVarSafe is a helper function that returns the requested variable from URI with allowSet
// providing input sanitization. If an error occurs, returns either a `MissingFieldError`
// or an `UnsafeFieldError`.
func GetVarSafe(r *http.Request, variableName string, allowSet AllowSet) (string, error) {
	vars := mux.Vars(r)
	variableValue, ok := vars[variableName]

	if !ok {
		return "", MissingFieldError{variableName}
	}

	err := allowSet.IsSafe(variableValue)
	if err != nil {
		return "", UnsafeFieldError{variableName, err.Error()}
	}

	return variableValue, nil
}