2015-04-21 17:51:01 +08:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2015-05-01 21:49:19 +08:00
|
|
|
"errors"
|
|
|
|
"io"
|
|
|
|
"net/http"
|
2015-07-11 00:29:22 +08:00
|
|
|
"net/url"
|
2015-07-08 16:45:28 +08:00
|
|
|
"os"
|
2015-05-04 00:01:54 +08:00
|
|
|
"time"
|
2015-05-01 21:49:19 +08:00
|
|
|
|
|
|
|
"github.com/antonholmquist/jason"
|
2015-04-21 17:51:01 +08:00
|
|
|
)
|
|
|
|
|
2015-05-02 00:13:23 +08:00
|
|
|
// ExpvarsUrl is the default url for fetching expvar info.
|
2015-07-11 00:29:22 +08:00
|
|
|
const ExpvarsPath = "/debug/vars"
|
2015-04-21 17:51:01 +08:00
|
|
|
|
2015-05-02 00:13:23 +08:00
|
|
|
// Expvar represents fetched expvar variable.
|
|
|
|
type Expvar struct {
|
|
|
|
*jason.Object
|
|
|
|
}
|
2015-04-21 17:51:01 +08:00
|
|
|
|
2015-07-08 16:45:28 +08:00
|
|
|
func getBasicAuthEnv() (user, password string) {
|
|
|
|
return os.Getenv("HTTP_USER"), os.Getenv("HTTP_PASSWORD")
|
|
|
|
}
|
|
|
|
|
2015-05-01 21:49:19 +08:00
|
|
|
// FetchExpvar fetches expvar by http for the given addr (host:port)
|
2015-07-11 00:29:22 +08:00
|
|
|
func FetchExpvar(u url.URL) (*Expvar, error) {
|
2015-05-02 00:13:23 +08:00
|
|
|
e := &Expvar{&jason.Object{}}
|
2015-05-04 00:01:54 +08:00
|
|
|
client := &http.Client{
|
|
|
|
Timeout: 1 * time.Second, // TODO: make it configurable or left default?
|
|
|
|
}
|
2015-07-08 16:45:28 +08:00
|
|
|
|
2015-07-11 00:29:22 +08:00
|
|
|
req, _ := http.NewRequest("GET", "localhost", nil)
|
|
|
|
req.URL = &u
|
|
|
|
req.Host = u.Host
|
|
|
|
|
2015-07-08 16:45:28 +08:00
|
|
|
if user, pass := getBasicAuthEnv(); user != "" && pass != "" {
|
|
|
|
req.SetBasicAuth(user, pass)
|
|
|
|
}
|
|
|
|
resp, err := client.Do(req)
|
2015-05-01 21:49:19 +08:00
|
|
|
if err != nil {
|
2015-05-02 00:13:23 +08:00
|
|
|
return e, err
|
2015-05-01 21:49:19 +08:00
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode == http.StatusNotFound {
|
2015-05-02 00:13:23 +08:00
|
|
|
return e, errors.New("Vars not found. Did you import expvars?")
|
|
|
|
}
|
|
|
|
|
2015-05-02 05:03:50 +08:00
|
|
|
expvar, err := ParseExpvar(resp.Body)
|
2015-05-02 00:13:23 +08:00
|
|
|
if err != nil {
|
|
|
|
return e, err
|
2015-05-01 21:49:19 +08:00
|
|
|
}
|
2015-05-02 05:03:50 +08:00
|
|
|
e = expvar
|
2015-05-02 00:13:23 +08:00
|
|
|
return e, nil
|
2015-04-21 17:51:01 +08:00
|
|
|
}
|
|
|
|
|
2015-05-02 00:13:23 +08:00
|
|
|
// ParseExpvar parses expvar data from reader.
|
|
|
|
func ParseExpvar(r io.Reader) (*Expvar, error) {
|
|
|
|
object, err := jason.NewObjectFromReader(r)
|
|
|
|
return &Expvar{object}, err
|
2015-04-21 17:51:01 +08:00
|
|
|
}
|