expvarmon/expvars.go

48 lines
1012 B
Go
Raw Normal View History

2015-04-21 17:51:01 +08:00
package main
import (
2015-05-01 21:49:19 +08:00
"errors"
"io"
"net/http"
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.
const ExpvarsURL = "/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-05-01 21:49:19 +08:00
// FetchExpvar fetches expvar by http for the given addr (host:port)
2015-05-02 00:13:23 +08:00
func FetchExpvar(addr string) (*Expvar, error) {
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?
}
resp, err := client.Get(addr)
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
}