Commits

Miki Tebeka committed 7b6757f

Some logging and close local socket on error

Comments (0)

Files changed (1)

 	"flag"
 	"fmt"
 	"io"
+	"log"
 	"net"
 	"net/http"
 	"os"
 
 func main() {
 	flag.Usage = func() {
-		fmt.Fprintf(os.Stderr, "usage: seamless LISTEN_ADDR BACKEND\n")
+		fmt.Fprintf(os.Stderr, "usage: seamless LISTEN_PORT BACKEND\n")
 		fmt.Fprintf(os.Stderr, "command line switches:\n")
 		flag.PrintDefaults()
 	}
 		flag.Usage()
 		os.Exit(1)
 	}
-	localAddr := flag.Arg(0)
+	localAddr := fmt.Sprintf(":%s", flag.Arg(0))
 	backend = flag.Arg(1)
 
 	local, err := net.Listen("tcp", localAddr)
 		die(fmt.Sprintf("cannot listen: %v", err))
 	}
 
-	go runHttpServer(*port)
+	go startHttpServer(*port)
 
 	for {
 		conn, err := local.Accept()
 func forward(local net.Conn, remoteAddr string) {
 	remote, err := net.Dial("tcp", remoteAddr)
 	if remote == nil {
-		fmt.Fprintf(os.Stderr, "remote dial failed: %v\n", err)
+		log.Printf("remote dial failed: %v\n", err)
+		local.Close()
 		return
 	}
 	go io.Copy(local, remote)
 	os.Exit(1)
 }
 
-func runHttpServer(port int) {
+func startHttpServer(port int) {
 	http.HandleFunc("/switch", switchHandler)
 	http.HandleFunc("/current", currentHandler)
 	http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
 func switchHandler(w http.ResponseWriter, req *http.Request) {
 	newBackend := req.FormValue("backend")
 	if len(newBackend) == 0 {
-		http.Error(w, "missing 'backend' parameter", http.StatusBadRequest)
+		msg := "error: missing 'backend' parameter"
+		log.Println(msg)
+		http.Error(w, msg, http.StatusBadRequest)
 		return
 	}
 	backend = newBackend
 }
 
 func currentHandler(w http.ResponseWriter, req *http.Request) {
+	w.Header().Set("Content-Type", "text/plain")
 	fmt.Fprintf(w, "%s\n", backend)
 }