Go浪文件下载代理

直接代码

Copy
package main

import (
"bytes"
"fmt"
"io"
"log"
"net"
"net/url"
"strings"
)

func App() {
listener, err := net.Listen("tcp", ":9999")
if err != nil {
println("启动失败， ", err.Error())
}
for {
client, err := listener.Accept()
println("new client……")
if err != nil {
println("accept failed, ", err.Error())
}
// dealing with clients' requests
go func() {
var b [1024]byte
n, err := client.Read(b[:])
if err != nil {
println("read head failed,", err.Error())
}
var method, host, address string
println(string(b[:]))
fmt.Sscanf(string(b[:bytes.IndexByte(b[:], '\n')]), "%s%s", &method, &host)
hostPortURL, err := url.Parse(host)
if err != nil {
log.Println(err)
return
}
if hostPortURL.Opaque == "443" { //https访问
address = hostPortURL.Scheme + ":443"
} else { //http访问
if strings.Index(hostPortURL.Host, ":") == -1 { //host不带端口， 默认80
address = hostPortURL.Host + ":80"
} else {
address = hostPortURL.Host
}
}
server, err := net.Dial("tcp", address)
if err != nil {
log.Println(err)
return
}
if method == "CONNECT" {
fmt.Fprint(client, "HTTP/1.1 200 Connection established\r\n\r\n")
} else {
server.Write(b[:n])
}
//进行转发
go io.Copy(server, client)
io.Copy(client, server)
}()
}
}

func main() {
App()
}