Add 500 response codes on errors

master
Buddy Sandidge 5 years ago
parent e0048be74c
commit b42ee353fe

@ -18,8 +18,8 @@ import (
// App context
type App struct {
cli *cli.App
client *client.Client
out io.Writer
Client *client.Client
Out io.Writer
}
var (
@ -60,7 +60,7 @@ var (
func New() *App {
cliapp := cli.NewApp()
app := &App{
out: os.Stdout,
Out: os.Stdout,
cli: cliapp,
}
@ -79,19 +79,19 @@ func New() *App {
cli.Command{
Name: "print",
Usage: "pretty prints api result",
Action: app.actionPrint,
Action: app.ActionPrint,
},
cli.Command{
Name: "export",
Usage: "runs http exporter for prometheus",
Action: app.actionMetrics,
Action: app.ActionMetrics,
Flags: []cli.Flag{
FlagInterface,
},
},
}
app.cli.Before = app.before
app.cli.Before = app.Before
return app
}
@ -101,8 +101,8 @@ func (a *App) Run(args []string) error {
}
// Before sets up app
func (a *App) before(ctx *cli.Context) error {
a.client = &client.Client{
func (a *App) Before(ctx *cli.Context) error {
a.Client = &client.Client{
URL: url.URL{
Scheme: ctx.String("scheme"),
Host: ctx.String("host"),
@ -112,30 +112,41 @@ func (a *App) before(ctx *cli.Context) error {
return nil
}
func (a *App) actionPrint(_ *cli.Context) error {
node, err := a.client.Fetch()
// ActionPrint prints api result
func (a *App) ActionPrint(_ *cli.Context) error {
node, err := a.Client.Fetch()
if err != nil {
return err
}
fmt.Fprint(a.out, node.Stringify())
fmt.Print(a.Out, node.Stringify())
return nil
}
func (a *App) actionMetrics(ctx *cli.Context) error {
// ActionMetrics serves http
func (a *App) ActionMetrics(ctx *cli.Context) error {
addr := ctx.String("http")
http.HandleFunc("/metrics", func(resp http.ResponseWriter, req *http.Request) {
http.HandleFunc("/metrics", a.HandleMetrics)
log.Println(a.Out, "listen on: "+addr)
return http.ListenAndServe(addr, nil)
}
// HandleMetrics handler
func (a *App) HandleMetrics(resp http.ResponseWriter, req *http.Request) {
log.Println("GET /metrics")
root, err := a.client.Fetch()
root, err := a.Client.Fetch()
if err != nil {
http.Error(resp, err.Error(), http.StatusInternalServerError)
return
}
vals, err := root.Values()
if err != nil {
http.Error(resp, err.Error(), http.StatusInternalServerError)
return
}
collection := metrics.FromVals(vals)
registry := prometheus.NewRegistry()
if err := registry.Register(collection); err != nil {
http.Error(resp, err.Error(), http.StatusInternalServerError)
return
}
@ -145,7 +156,4 @@ func (a *App) actionMetrics(ctx *cli.Context) error {
handler.ServeHTTP(resp, req)
registry.Unregister(collection)
})
log.Println("listen on: " + addr)
return http.ListenAndServe(addr, nil)
}

Loading…
Cancel
Save