-
-
Save pjstorm/3a904f12dfcc5c943b3b to your computer and use it in GitHub Desktop.
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
package main | |
import ( | |
"bufio" | |
"fmt" | |
"io" | |
"net" | |
"strings" | |
) | |
func main() { | |
listener, err := net.ListenTCP("tcp", &net.TCPAddr{Port: 8080}) | |
if err != nil { | |
fmt.Printf("failed to listen on :8080: %s\n", err) | |
return | |
} | |
for { | |
c, err := listener.AcceptTCP() | |
if err != nil { | |
fmt.Printf("failed to accept: %s\n", err) | |
return | |
} | |
go service(c) | |
} | |
} | |
func service(c *net.TCPConn) { | |
defer c.Close() | |
c.SetReadTimeout(60 * 1000 * 1000 * 1000) | |
lines := bufio.NewReader(c) | |
headerBytes, isPrefix, err := lines.ReadLine() | |
if err != nil || isPrefix { | |
return | |
} | |
header := string(headerBytes) | |
for { | |
l, _, err := lines.ReadLine() | |
if err != nil { | |
return | |
} | |
if len(l) == 0 { | |
break | |
} | |
} | |
fmt.Printf("%s\n", header) | |
parts := strings.Split(header, " ", -1) | |
if parts[0] != "CONNECT" { | |
c.Write([]byte("HTTP/1.1 500 Server Error\r\n\r\nServer Error.\r\n")) | |
return | |
} | |
fmt.Printf("connecting to %s\n", parts[1]) | |
out, err := net.Dial("tcp", parts[1]) | |
if err != nil { | |
fmt.Printf("failed to connect to %s\n", parts[1]) | |
return | |
} | |
c.Write([]byte("HTTP/1.1 200 Connected ok\r\n\r\n")) | |
go io.Copy(out, lines) | |
io.Copy(c, out) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment