1
0
mirror of https://github.com/divan/expvarmon.git synced 2025-04-27 13:48:55 +08:00
expvarmon/expvars.go

58 lines
1.2 KiB
Go
Raw Normal View History

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