douao1858 2018-10-10 15:31
浏览 15
已采纳

从net.Conn检索URI路径

I'm working with someone else's code and I need some assistance.

Here we have a tcp load balancer. What I need is access to the request uri from this piece of code before we do the net dial.

I looked through the API Documentation here: https://golang.org/pkg/net/ but was unable to find any relevant methods under the net.Conn namespace for retrieving the current request path.

func copy(wc io.WriteCloser, r io.Reader) {
    defer wc.Close()
    io.Copy(wc, r)    
}

func handleConnection(us net.Conn, backend BA.Backend) {
    if backend == nil {
        log.Printf("no backend available for connection from %s", us.RemoteAddr())
        us.Close()
        return
    }           

    ip:=us.RemoteAddr().String()
    parts:=strings.Split(ip,":")
    ip=parts[0]

    //w := bufio.NewWriter(us)
    //w.WriteString(+"
")
    //w.Flush()    
    ds, err := net.Dial("tcp", backend.String())
    if err != nil {
        log.Printf("failed to dial %s: %s", backend, err)
        us.Close()
        return
    }

    // Ignore errors
    go copy(ds, us)
    go copy(us, ds)
}

func tcpBalance(bind string, backends BA.Backends) error {    
    log.Println("using tcp balancing")
    ln, err := net.Listen("tcp", bind)
    if err != nil {
        return fmt.Errorf("failed to bind: %s", err)
    }

    log.Printf("listening on %s, balancing %d backends", bind, backends.Len())

    for {
        conn, err := ln.Accept()
        if err != nil {
            log.Printf("failed to accept: %s", err)
            continue
        }        
        go handleConnection(conn, backends.Choose())
    }

    return err
}
  • 写回答

1条回答 默认 最新

  • douzhi6365 2018-10-10 15:35
    关注

    This is not possible because not every TCP connection is an HTTP connection and the TCP protocol has no concept of URIs. Many other protocols are built on TCP and it's not that protocol's responsibility to know about them.

    HTTP is an Application Layer (layer 7) protocol which uses the TCP Transport Layer (layer 4) protocol. As such, TCP connections have no concept of HTTP because lower layer protocols have no concept of the layers that may be built on top of them.

    You can learn more by reading about the OSI model.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧