feat: Implement simple page metrics
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
This commit is contained in:
56
internal/pages/metrics.go
Normal file
56
internal/pages/metrics.go
Normal file
@@ -0,0 +1,56 @@
|
||||
package pages
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type LokiMetricConfig struct {
|
||||
Url string
|
||||
Enabled bool
|
||||
}
|
||||
|
||||
// Checks if we should send a metric ping to Loki based on the served path.
|
||||
func (c *LokiMetricConfig) shouldSendMetrics(path string) bool {
|
||||
return strings.HasSuffix(path, ".html") && c.Enabled
|
||||
}
|
||||
|
||||
func (c *LokiMetricConfig) sendMetricPing(domain, path string) {
|
||||
data := map[string]interface{}{
|
||||
"steams": []map[string]interface{}{
|
||||
{
|
||||
"stream": map[string]string{
|
||||
// Labels
|
||||
"service": "rio",
|
||||
"domain": domain,
|
||||
"type": "metric",
|
||||
},
|
||||
"values": [][]interface{}{
|
||||
{
|
||||
strconv.Itoa(int(time.Now().UnixNano())),
|
||||
"path=" + path,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
jsonData, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
log.Errorf("Failed to send metric ping to Loki: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Send the ping to the Loki server
|
||||
go func() {
|
||||
http.Post(
|
||||
c.Url,
|
||||
"application/json",
|
||||
strings.NewReader(string(jsonData)),
|
||||
)
|
||||
}()
|
||||
}
|
||||
@@ -45,7 +45,7 @@ func addHeaders(csp, contentType string, contentLength int, w http.ResponseWrite
|
||||
}
|
||||
}
|
||||
|
||||
func ServeFile(username, reponame, path, defaultCsp string, giteaClient *repo.GiteaClient, w http.ResponseWriter) {
|
||||
func ServeFile(username, reponame, path, defaultCsp, domain string, giteaClient *repo.GiteaClient, metricConfig *LokiMetricConfig, w http.ResponseWriter) {
|
||||
// Strip away a starting / as it messes with Gitea
|
||||
if path[:1] == "/" {
|
||||
path = path[1:]
|
||||
@@ -116,4 +116,9 @@ func ServeFile(username, reponame, path, defaultCsp string, giteaClient *repo.Gi
|
||||
addHeaders(csp, mimeType, len(content), w)
|
||||
w.WriteHeader(200)
|
||||
w.Write(content)
|
||||
|
||||
// Tell Loki about if, if desired
|
||||
if metricConfig.shouldSendMetrics(path) {
|
||||
metricConfig.sendMetricPing(domain, path)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user