Created
March 12, 2013 04:38
-
-
Save physacco/5140412 to your computer and use it in GitHub Desktop.
This is a simple netcat implementation in go.
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
/* | |
* This is a simple netcat implementation in go. | |
* Test this program in terminal: | |
* | |
* $ go run simplerouter.go | |
* GET / HTTP/1.0<CR> | |
* <CR> | |
* HTTP/1.0 302 Found | |
* ... | |
* | |
*/ | |
package main | |
import ( | |
"io" | |
"os" | |
"log" | |
"net" | |
"strings" | |
) | |
var quit chan bool | |
func io2io(src io.Reader, dst io.Writer) { | |
defer func() { quit <- true }() | |
buf := make([]byte, 8192) | |
for { | |
n, err := src.Read(buf) | |
if err != nil { | |
if err != io.EOF { | |
log.Println("read error:", err) | |
} | |
break | |
} | |
str := strings.Replace(string(buf[:n]), "\n", "\r\n", -1) | |
_, err = dst.Write([]byte(str)) | |
if err != nil { | |
log.Println("write error:", err) | |
break | |
} | |
} | |
} | |
func main() { | |
quit = make(chan bool) | |
conn, err := net.Dial("tcp", "www.google.com:80") | |
if err != nil { | |
log.Println("failed to connect:", err) | |
os.Exit(1) | |
} | |
go io2io(os.Stdin, conn) | |
go io2io(conn, os.Stdout) | |
select { | |
case <-quit: | |
return | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment