1

我打算用libp2p实现一个经典的HLS示例,如下 https://hackernoon.com/building-a-media-streaming-server-using-go-and-hls-protocol-j85h3wem 但是我遇到了以下错误:</p>

404页面不存在

我构建 linsten 的代码:

m1, _ := multiaddr.NewMultiaddr("/ip4/127.0.0.1/tcp/1000")
    m2, _ := multiaddr.NewMultiaddr("/ip4/127.0.0.1/tcp/1001")
    srvHost := NewHost(m1)
    clientHost := NewHost(m2)
    defer srvHost.Close()
    defer clientHost.Close()

    srvHost.Peerstore().AddAddrs(clientHost.ID(), clientHost.Addrs(), peerstore.PermanentAddrTTL)
    fmt.Println("id is", clientHost.ID())
    fmt.Println("addr is", srvHost.Addrs())
    clientHost.Peerstore().AddAddrs(srvHost.ID(), srvHost.Addrs(), peerstore.PermanentAddrTTL)

    listener, err := gostream.Listen(srvHost, "/testiti-test")
    if err != nil {
        panic(err)
    }
    defer listener.Close()

我的代码构建客户端:

tr := &http.Transport{}
    tr.RegisterProtocol("libp2p", p2phttp.NewTransport(clientHost, p2phttp.ProtocolOption("/testiti-test")))
client := &http.Client{Transport: tr}

res, err := client.Get(fmt.Sprintf("libp2p://%s/simple", port))
if err != nil {
    panic(err)
}
data, err := ioutil.ReadAll(res.Body)
defer res.Body.Close()
if err != nil {
    log.Fatal(err)
}
fmt.Println(string(data))

我的代码构建服务器:

go func() {
        http.HandleFunc("/simple", addHeaders(http.FileServer(http.Dir(songsDir))))
        //http.HandleFunc("/simple", addHeaders2())
        fmt.Printf("Starting server on %v\n", port)
        log.Printf("Serving %s on HTTP port: %v\n", songsDir, port)

        server := &http.Server{}
        server.Serve(listener)
    }()
func addHeaders(h http.Handler) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Access-Control-Allow-Origin", "*")
        h.ServeHTTP(w, r)
    }
}

新主机:

func NewHost(listen multiaddr.Multiaddr) host.Host {
    h, err := libp2p.New(
        libp2p.ListenAddrs(listen),
    )
    if err != nil {
        panic(err)
    }
    return h
}
4

1 回答 1

0

问题是由路由引起的。对于 http.FileServer,"\simple" 表示目录而不是 url。所以只需像这样修复:

url := fmt.Sprintf("libp2p://%s/origin.m3u8", port)
res, err := client.Get(url)
if err != nil {
    panic(err)
}
data, err := ioutil.ReadAll(res.Body)
defer res.Body.Close()
if err != nil {
    log.Fatal(err)
}
fmt.Println(string(data))
于 2022-02-14T07:56:40.970 回答