Skip to content

Instantly share code, notes, and snippets.

@gaurish
Created March 20, 2017 21:46
Show Gist options
  • Save gaurish/2e390bdedc0ed8d3f0261320fee67196 to your computer and use it in GitHub Desktop.
Save gaurish/2e390bdedc0ed8d3f0261320fee67196 to your computer and use it in GitHub Desktop.
Returns redis memory info as JSON over HTTP for monitoring
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"strings"
"fmt"
"github.com/garyburd/redigo/redis"
)
// ParseRedisLine parses a single line returned by INFO
func ParseRedisLine(s string, delimeter string) []string {
return strings.Split(s, delimeter)
}
// ParseRedisInfo parses the string returned by the INFO command
// Every line is split up into key and value
func ParseRedisInfo(info string) map[string]string {
// Feed every line into
result := strings.Split(info, "\r\n")
// Load redis info values into array
values := map[string]string{}
for _, value := range result {
// Values are separated by :
parts := ParseRedisLine(value, ":")
if len(parts) == 2 {
values[parts[0]] = parts[1]
}
}
return values
}
func main() {
conn, err := redis.DialURL(os.Getenv("REDIS_URL"))
var port string
port = os.Getenv("PORT")
if len(port) == 0 {
port = "8888"
}
if err != nil {
log.Fatal(err)
}
defer conn.Close()
http.HandleFunc("/info", func(w http.ResponseWriter, r *http.Request) {
info, err := redis.String(conn.Do("INFO", "memory"))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(ParseRedisInfo(info))
})
log.Fatal(http.ListenAndServe(fmt.Sprint(":", port), nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment