Skip to content

Instantly share code, notes, and snippets.

@gaurish
Created February 2, 2018 10:34
Show Gist options
  • Save gaurish/6f8adf699e07834bea927a01e6748bcd to your computer and use it in GitHub Desktop.
Save gaurish/6f8adf699e07834bea927a01e6748bcd to your computer and use it in GitHub Desktop.
Redis Info as JSON over HTTP powered by Go
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