Pushgateway go get & push
Jump to navigation
Jump to search
./g -blackbox-url="http://blackbox.example.com:9115/probe?target=https://google.com&module=http_2xx" -pushgateway-url="https://pushgateway.example.com/metrics/job/pushdemo" -username=myuser -password=mypass
package main import ( "bytes" "flag" "fmt" "io/ioutil" "net/http" ) func fetchMetrics(url, username, password string) ([]byte, error) { client := &http.Client{} req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } if username != "" && password != "" { req.SetBasicAuth(username, password) } resp, err := client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() return ioutil.ReadAll(resp.Body) } func pushMetrics(url, username, password string, metrics []byte) error { client := &http.Client{} req, err := http.NewRequest("POST", url, bytes.NewBuffer(metrics)) if err != nil { return err } if username != "" && password != "" { req.SetBasicAuth(username, password) } resp, err := client.Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode >= 400 { body, _ := ioutil.ReadAll(resp.Body) return fmt.Errorf("error pushing metrics: %s", body) } return nil } func main() { blackboxURL := flag.String("blackbox-url", "", "URL of the Blackbox Exporter") pushgatewayURL := flag.String("pushgateway-url", "", "URL of the Pushgateway") username := flag.String("username", "", "Optional username for Basic Auth") password := flag.String("password", "", "Optional password for Basic Auth") flag.Parse() if *blackboxURL == "" || *pushgatewayURL == "" { fmt.Println("Both blackbox-url and pushgateway-url are required") return } metrics, err := fetchMetrics(*blackboxURL, *username, *password) if err != nil { fmt.Printf("Error fetching metrics: %v\n", err) return } err = pushMetrics(*pushgatewayURL, *username, *password, metrics) if err != nil { fmt.Printf("Error pushing metrics: %v\n", err) return } fmt.Println("Metrics pushed successfully") }