82 lines
1.1 KiB
Go
82 lines
1.1 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"errors"
|
|
"io"
|
|
"log"
|
|
"os"
|
|
)
|
|
|
|
var (
|
|
errNoInput = errors.New("input undefined")
|
|
errMultipleInputs = errors.New("multiple inputs defined")
|
|
errInvalidFilename = errors.New("invalid filename")
|
|
)
|
|
|
|
func noop() {}
|
|
|
|
func initInput(
|
|
filename, stringValue *string, stdin io.Reader, args []string,
|
|
) (
|
|
input io.Reader, finalize func(), err error,
|
|
) {
|
|
finalize = noop
|
|
|
|
var inputCount int
|
|
if filename != nil {
|
|
inputCount++
|
|
}
|
|
|
|
if stringValue != nil {
|
|
inputCount++
|
|
}
|
|
|
|
if len(args) > 0 {
|
|
inputCount++
|
|
}
|
|
|
|
if inputCount > 1 {
|
|
err = errMultipleInputs
|
|
return
|
|
}
|
|
|
|
if len(args) > 0 {
|
|
filename = new(string)
|
|
*filename = args[0]
|
|
}
|
|
|
|
switch {
|
|
case filename != nil:
|
|
if *filename == "" {
|
|
err = errInvalidFilename
|
|
return
|
|
}
|
|
|
|
var f io.ReadCloser
|
|
f, err = os.Open(*filename)
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
finalize = func() {
|
|
if err := f.Close(); err != nil {
|
|
log.Fatalln(err)
|
|
}
|
|
}
|
|
|
|
input = f
|
|
case stringValue != nil:
|
|
input = bytes.NewBufferString(*stringValue)
|
|
default:
|
|
if stdin == nil {
|
|
err = errNoInput
|
|
return
|
|
}
|
|
|
|
input = stdin
|
|
}
|
|
|
|
return
|
|
}
|