Add support for multiple screen_names

This commit is contained in:
Sam W 2022-08-04 14:43:06 +03:00
parent 8bb530758c
commit 69dfbca7b2
1 changed files with 20 additions and 16 deletions

36
main.go
View File

@ -7,6 +7,7 @@ import (
"fmt"
"net/http"
"net/url"
"strings"
"time"
"github.com/prometheus/client_golang/prometheus"
@ -14,15 +15,7 @@ import (
log "github.com/sirupsen/logrus"
)
func probeTwitter(ctx context.Context, target string, registry *prometheus.Registry) (success bool) {
followersGauge := prometheus.NewGaugeVec(prometheus.GaugeOpts{
Name: "twitter_followers",
Help: "The number of followers of the twitter account.",
},
[]string{"screen_name"})
registry.MustRegister(followersGauge)
func probeTwitterFollowers(ctx context.Context, target string, gauge *prometheus.GaugeVec) (success bool) {
res, err := http.Get(fmt.Sprintf("https://cdn.syndication.twimg.com/widgets/followbutton/info.json?screen_names=%s", url.QueryEscape(target)))
if err != nil {
log.Errorf("fetching url: %s", err)
@ -44,24 +37,35 @@ func probeTwitter(ctx context.Context, target string, registry *prometheus.Regis
log.Errorf("Unexpected (>1) results returned. WTF twitter??")
return false
}
followersGauge.With(prometheus.Labels{"screen_name": target}).Set(float64(data[0].FollowersCount))
gauge.With(prometheus.Labels{"screen_name": target}).Set(float64(data[0].FollowersCount))
return true
}
func twitterHandler(w http.ResponseWriter, r *http.Request) {
screenName := r.URL.Query().Get("screen_name")
if screenName == "" {
reg := prometheus.NewRegistry()
followersGauge := prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "twitter_followers",
Help: "The number of followers of the twitter account.",
},
[]string{"screen_name"},
)
reg.MustRegister(followersGauge)
screenNames := r.URL.Query().Get("screen_name")
if screenNames == "" {
http.Error(w, "screen_name parameter is missing", http.StatusBadRequest)
return
}
reg := prometheus.NewRegistry()
ctx, cancel := context.WithTimeout(r.Context(), time.Duration(5*time.Second))
defer cancel()
if success := probeTwitter(ctx, screenName, reg); !success {
log.Error("Probe failed!")
for _, screenName := range strings.Split(screenNames, ",") {
if success := probeTwitterFollowers(ctx, screenName, followersGauge); !success {
log.Error("Probe for screenname %s failed!", screenName)
}
}
h := promhttp.HandlerFor(reg, promhttp.HandlerOpts{})