I intend to implement a classic HLS example with libp2p, which is as follows https://hackernoon.com/building-a-media-streaming-server-using-go-and-hls-protocol-j85h3wem But I encountered the following errors:
404 page not found
My code constructing 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()
My code constructing client:
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))
My code constructing sever:
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)
}
}
New host:
func NewHost(listen multiaddr.Multiaddr) host.Host {
h, err := libp2p.New(
libp2p.ListenAddrs(listen),
)
if err != nil {
panic(err)
}
return h
}
CodePudding user response:
The problem is casued by routing.For a http.FileServer,"\simple" means a dir but not a url.So just fix like this:
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))