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 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分