Skip to content

Instantly share code, notes, and snippets.

@peterhellberg
Created October 28, 2012 01:01
Show Gist options
  • Select an option

  • Save peterhellberg/3967081 to your computer and use it in GitHub Desktop.

Select an option

Save peterhellberg/3967081 to your computer and use it in GitHub Desktop.
A small loadbalancer API written in Go (Using Pat and Redigo)
package main
import (
"io"
"fmt"
"time"
"net/http"
"encoding/json"
"github.com/bmizerany/pat"
"github.com/garyburd/redigo/redis"
)
type LoadbalancerResponse struct {
Redirect string `json:"redirect"`
Timestamp int64 `json:"timestamp"`
}
func LoadbalancerServer(w http.ResponseWriter, req *http.Request) {
// Connect to Redis
c, err := redis.Dial("tcp", ":6379")
if err != nil {
fmt.Println("Error:", err)
}
defer c.Close()
redirect_ip, err := redis.String(c.Do("GET", "redirect_ip"))
if err != nil {
fmt.Println("Error:", err)
}
// Populate the loadbalancer response struct
response := LoadbalancerResponse{
Redirect: redirect_ip,
Timestamp: time.Now().Unix(),
}
// Marshal the JSON
json, err := json.Marshal(response)
if err != nil {
fmt.Println("Error:", err)
}
// Return the JSON to the client
io.WriteString(w, string(json))
}
func main() {
m := pat.New()
m.Get("/loadbalancer.json", http.HandlerFunc(LoadbalancerServer))
http.Handle("/", m)
http.ListenAndServe(":12345", nil)
}
@peterhellberg
Copy link
Author

I’m just playing around here… probably doing a lot of mistakes :)

The initial idea for this API is outlined in this article: http://c7.se/tiny-api-with-nginx/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment