zoukankan      html  css  js  c++  java
  • 一个简单的Golang实现的HTTP Proxy方法

    package main
    
    import (
      "bytes"
      "fmt"
      "io"
      "log"
      "net"
      "net/url"
      "strings"
    )
    
    func main() {
      log.SetFlags(log.LstdFlags|log.Lshortfile)
      l, err := net.Listen("tcp", ":8081")
      if err != nil {
        log.Panic(err)
      }
    
      for {
        client, err := l.Accept()
        if err != nil {
          log.Panic(err)
        }
    
        go handleClientRequest(client)
      }
    }
    
    func handleClientRequest(client net.Conn) {
      if client == nil {
        return
      }
      defer client.Close()
    
      var b [1024]byte
      n, err := client.Read(b[:])
      if err != nil {
        log.Println(err)
        return
      }
      var method, host, address string
      fmt.Sscanf(string(b[:bytes.IndexByte(b[:], '
    ')]), "%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
        }
      }
    
      //获得了请求的host和port,就开始拨号吧
      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
    ")
      } else {
        server.Write(b[:n])
      }
      //进行转发
      go io.Copy(server, client)
      io.Copy(client, server)
    }
    

      

  • 相关阅读:
    uva 10369 Arctic Network
    uvalive 5834 Genghis Khan The Conqueror
    uvalive 4848 Tour Belt
    uvalive 4960 Sensor Network
    codeforces 798c Mike And Gcd Problem
    codeforces 796c Bank Hacking
    codeforces 768c Jon Snow And His Favourite Number
    hdu 1114 Piggy-Bank
    poj 1276 Cash Machine
    bzoj 2423 最长公共子序列
  • 原文地址:https://www.cnblogs.com/ip99/p/14587790.html
Copyright © 2011-2022 走看看