Created
January 30, 2014 13:36
-
-
Save ProTip/8708448 to your computer and use it in GitHub Desktop.
This file contains 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
func (s *Server) sqlHandler(w http.ResponseWriter, req *http.Request) { | |
//http.Error(w, "Bah", http.StatusBadRequest) | |
//return | |
query, err := ioutil.ReadAll(req.Body) | |
if err != nil { | |
log.Printf("Couldn't read body: %s", err) | |
http.Error(w, err.Error(), http.StatusBadRequest) | |
} | |
out, err := s.raftServer.Do(command.NewSqlQuery(string(query))) | |
if err != nil { | |
//http.Error(w, err.Error(), http.StatusBadRequest) | |
//return | |
log.Println("Raft: ", err.Error()) | |
if strings.Contains(err.Error(), "Not current leader") { | |
leaderName := s.raftServer.Leader() | |
if leaderName == "" { | |
//http.Error(w, "Proxy: Tried to proxy but no leader!", http.StatusBadRequest) | |
http.Error(w, err.Error(), http.StatusBadRequest) | |
return | |
} | |
var leaderEncoded string | |
if val, ok := s.raftServer.Peers()[leaderName]; ok { | |
leaderEncoded = val.ConnectionString | |
log.Println("Proxy: Found leader at: ", leaderEncoded) | |
} else { | |
http.Error(w, err.Error(), http.StatusBadRequest) | |
return | |
} | |
proxyReader := bytes.NewReader(query) | |
log.Println("Proxy: SafePost starting") | |
resp, err := s.client.SafePost(leaderEncoded, "/sql", proxyReader) | |
if err != nil { | |
log.Println("Proxy failed: ", err.Error()) | |
http.Error(w, err.Error(), http.StatusBadRequest) | |
} | |
respBytes, err := ioutil.ReadAll(resp) | |
if err != nil { | |
http.Error(w, err.Error(), http.StatusBadRequest) | |
} | |
w.Write(respBytes) | |
return | |
} | |
} | |
output := out.(*sql.Output) | |
formatted := fmt.Sprintf("SequenceNumber: %d\n%s", | |
output.SequenceNumber, output.Stdout) | |
w.Write([]byte(formatted)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment