使用libp2p-http构建HLS的问题

Troubles on constructing HLS using libp2p-http

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

404 page not found

我的构造 linstening 的代码:

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
}

问题是由 routing.For http.FileServer 引起的,"\simple" 表示目录而不是 url.So 只需像这样修复:

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))