Ejemplo n.º 1
0
func (r *Request) setParams() {
	params := make(map[string]interface{})
	switch ct := r.contentType(); {
	case ct == "application/json":
		if r.Body != nil {
			raw, err := ioutil.ReadAll(r.Body)
			defer r.Body.Close()
			if err != nil {
				return
			}
			err = json.Unmarshal(raw, &params)
			r.RawJson = raw
			if err != nil {
				env.Log("Unable to deserialize JSON payload: ", err, string(raw))
				return
			}
		}
	case strings.HasPrefix(ct, "multipart/form-data"):
		err := r.ParseMultipartForm(10 * 1024 * 1024)
		if err != nil {
			return
		}
		unpackValues(params, r.MultipartForm.Value)
	default:
		err := r.ParseForm()
		if err != nil {
			return
		}
		unpackValues(params, r.Form)
	}
	r.Params = params
}
Ejemplo n.º 2
0
// Handler returns a func encapsulating the Gadget router (and corresponding
// controllers that can be used in a call to http.HandleFunc. Handler must be
// invoked only after Routes has been called and all Controllers have been
// registered.
//
// In theory, Gadget users will not ever have to call Handler, as Gadget will
// set up http.HandleFunc to use its return value.
func (a *App) Handler() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var final string
		req := newRequest(r)
		defer func() {
			if r := recover(); r != nil {
				trace := string(debug.Stack())
				lines := strings.Split(trace, "\n")
				trace = strings.Join(lines[6:], "\n")
				if env.Debug {
					a.write(w, req, nil, 500, trace, "")
				} else {
					a.write(w, req, nil, 500, nil, "")
					env.Log(trace)
				}
			}
		}()
		matched, status, body, action := a.match(req)
		if matched != nil && matched.handler != nil {
			matched.handler(w, r)
			return
		}
		if status == 301 || status == 302 {
			resp, ok := body.(*Response)
			if ok {
				final = resp.Body.(string)
			} else {
				final = body.(string)
				resp = NewResponse(final)
			}
			resp.Headers.Set("Location", final)
			resp.status = status
			resp.write(w)
			req.log(status, len(final))
			return
		}
		a.write(w, req, matched, status, body, action)
	}
}
Ejemplo n.º 3
0
func (r *Request) log(status, contentLength int) {
	env.Log(RequestLogger(r, status, contentLength))
}
Ejemplo n.º 4
0
func (r *Request) log(status, contentLength int) {
	raw := r.Request
	env.Log(fmt.Sprintf(`[%s] "%s %s %s" %d %d`, time.Now().Format(time.RFC822), r.Method, raw.URL.Path, raw.Proto, status, contentLength))
}