handler.go raw

   1  package fgprof
   2  
   3  import (
   4  	"fmt"
   5  	"net/http"
   6  	"strconv"
   7  	"time"
   8  )
   9  
  10  // Handler returns an http handler that takes an optional "seconds" query
  11  // argument that defaults to "30" and produces a profile over this duration.
  12  // The optional "format" parameter controls if the output is written in
  13  // Google's "pprof" format (default) or Brendan Gregg's "folded" stack format.
  14  func Handler() http.Handler {
  15  	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  16  		var seconds int
  17  		var err error
  18  		if s := r.URL.Query().Get("seconds"); s == "" {
  19  			seconds = 30
  20  		} else if seconds, err = strconv.Atoi(s); err != nil || seconds <= 0 {
  21  			w.WriteHeader(http.StatusBadRequest)
  22  			fmt.Fprintf(w, "bad seconds: %d: %s\n", seconds, err)
  23  			return
  24  		}
  25  
  26  		format := Format(r.URL.Query().Get("format"))
  27  		if format == "" {
  28  			format = FormatPprof
  29  		}
  30  
  31  		stop := Start(w, format)
  32  		defer stop()
  33  		time.Sleep(time.Duration(seconds) * time.Second)
  34  	})
  35  }
  36