Created
February 6, 2020 01:36
-
-
Save sergeyt/a270712f845a6d1c128b7793faad833c to your computer and use it in GitHub Desktop.
Quick HTTP to TCP workaround
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
package main | |
import ( | |
"bufio" | |
"fmt" | |
"io" | |
"io/ioutil" | |
"log" | |
"net" | |
"net/http" | |
) | |
func main() { | |
http.HandleFunc("/api/command", func(w http.ResponseWriter, r *http.Request) { | |
body, err := ioutil.ReadAll(r.Body) | |
if err != nil { | |
http.Error(w, fmt.Sprintf("ioutil.ReadAll failed: +v", err.Error()), http.StatusInternalServerError) | |
return | |
} | |
tcpAddr, err := net.ResolveTCPAddr("tcp", "core:6000") | |
if err != nil { | |
http.Error(w, fmt.Sprintf("ResolveTCPAddr failed: +v", err.Error()), http.StatusInternalServerError) | |
return | |
} | |
conn, err := net.DialTCP("tcp", nil, tcpAddr) | |
if err != nil { | |
http.Error(w, fmt.Sprintf("Dial failed: +v", err.Error()), http.StatusInternalServerError) | |
return | |
} | |
defer conn.Close() | |
_, err = conn.Write(body) | |
if err != nil { | |
http.Error(w, fmt.Sprintf("Write to server failed: +v", err.Error()), http.StatusInternalServerError) | |
return | |
} | |
reply, err := bufio.NewReader(conn).ReadString('\n') | |
if err != nil { | |
http.Error(w, fmt.Sprintf("Read from core failed: +v", err.Error()), http.StatusInternalServerError) | |
return | |
} | |
println("reply:") | |
println(string(reply)) | |
io.WriteString(w, reply) | |
}) | |
log.Fatal(http.ListenAndServe(":8000", nil)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment