ytdl-web/ytdl/cmdbuilder.go

53 lines
831 B
Go
Raw Normal View History

2023-05-23 18:44:05 -04:00
package ytdl
import (
"bytes"
"encoding/json"
"os/exec"
"go.fifitido.net/ytdl-web/ytdl/metadata"
)
func Exec(binary, url string, options ...Option) error {
2023-05-23 18:44:05 -04:00
opts := Options{
args: []string{url},
stdin: nil,
stdout: nil,
stderr: nil,
output: nil,
}
for _, opt := range options {
if err := opt(&opts); err != nil {
return err
}
}
cmd := exec.Command(binary, opts.args...)
2023-05-23 18:44:05 -04:00
if opts.stdin != nil {
cmd.Stdin = opts.stdin
}
if opts.stdout != nil {
cmd.Stdout = opts.stdout
}
if opts.stderr != nil {
cmd.Stderr = opts.stderr
}
if err := cmd.Run(); err != nil {
return err
}
buf, bufOk := opts.stdout.(*bytes.Buffer)
meta, metaOk := opts.output.(*metadata.Metadata)
if bufOk && metaOk {
if err := json.Unmarshal(buf.Bytes(), meta); err != nil {
return err
}
}
return nil
}