I am currently learning about named pipes in linux using golang and C. I wrote a small server program which read a named pipe:
mkfifo /tmp/namedpipe.ts
ffmpeg -i url -c copy /tmp/namedpipe.ts
and a web server application opening the pipe like this:
package main
import (
"bufio"
"net/http"
"fmt"
"io"
"log"
"os"
)
func main() {
f, err := os.Open("/tmp/namedpipe.ts")
if err != nil {
log.Println(err.Error())
return
}
defer f.Close()
http.HandleFunc("/test.ts", func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "video/MP2T")
w.Header().Add("Cache-Control", "no-store")
w.Header().Add("Connection", "close")
reader := bufio.NewReader(f)
for {
line, err := reader.ReadBytes('\n')
if err != nil {
log.Fatal("Couldn't read line, ", err)
}
w.Write(line)
}
})
log.Fatal(http.ListenAndServe(":8081", nil))
}
This works great as long as only one client connects to the pipe. It can both read and write. If I try to connect a second client, the code never exceeds the line
I would like to modify this code and add more than one client reading from Named Pipe at the same time without freezing an image and not crashing.
CodePudding user response:
I need a modified golang or clang code for this program. It has multiple connections http server read from a Named Pipes at the same time
CodePudding user response:
As you use an infinite loop so that should be one break statement once the customer/Client consumes the API after downloading the file from the API it should not be a part of the loop and inside error, there should be one check for EOF and at that moment you should be break
package main
import (
"bufio"
"io"
"log"
"net/http"
"os"
)
func main() {
f, err := os.Open("/tmp/namedpipe.ts")
if err != nil {
log.Println(err.Error())
return
}
defer f.Close()
http.HandleFunc("/test.ts", func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "video/MP2T")
w.Header().Add("Cache-Control", "no-store")
w.Header().Add("Connection", "close")
reader := bufio.NewReader(f)
for {
line, err := reader.ReadBytes('\n')
if err != nil {
if err == io.EOF {
break
}
log.Fatal("Couldn't read line, ", err)
}
w.Write(line)
}
})
log.Fatal(http.ListenAndServe(":8081", nil))
}