57 lines
914 B
Go
57 lines
914 B
Go
package ytdl
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"os/exec"
|
|
|
|
"go.fifitido.net/ytdl-web/pkg/ytdl/metadata"
|
|
)
|
|
|
|
func Exec(binary, url string, options ...Option) error {
|
|
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...)
|
|
|
|
if opts.stdin != nil {
|
|
cmd.Stdin = opts.stdin
|
|
}
|
|
|
|
if opts.stdout != nil {
|
|
cmd.Stdout = opts.stdout
|
|
}
|
|
|
|
var stderr = new(bytes.Buffer)
|
|
if opts.stderr != nil {
|
|
cmd.Stderr = stderr
|
|
}
|
|
|
|
if err := cmd.Run(); err != nil {
|
|
return &Error{
|
|
stderr: stderr.String(),
|
|
child: 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
|
|
}
|