Created
October 28, 2012 01:01
-
-
Save peterhellberg/3967081 to your computer and use it in GitHub Desktop.
A small loadbalancer API written in Go (Using Pat and Redigo)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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/