Add support for multiple screen_names

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

35
main.go
View File

@ -14,15 +14,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 +36,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, ok := r.URL.Query()["screen_name"]
if !ok {
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 screenNames {
if success := probeTwitterFollowers(ctx, screenName, followersGauge); !success {
log.Error("Probe for screenname %s failed!", screenName)
}
}
h := promhttp.HandlerFor(reg, promhttp.HandlerOpts{})