Skip to content

Instantly share code, notes, and snippets.

@physacco
Created March 12, 2013 04:38
Show Gist options
  • Save physacco/5140412 to your computer and use it in GitHub Desktop.
Save physacco/5140412 to your computer and use it in GitHub Desktop.
This is a simple netcat implementation in go.
/*
* 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