-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathio.go
50 lines (43 loc) · 1.01 KB
/
io.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package main
import (
"bufio"
"fmt"
"io/ioutil"
"os"
"path"
"strings"
"text/template"
)
func includeFile(dir string) func(filePath string) (string, error) {
return func(filePath string) (string, error) {
data, err := ioutil.ReadFile(path.Join(dir, filePath))
if err != nil {
return "", err
}
return string(data), nil
}
}
func readFromStdin() (string, error) {
scanner := bufio.NewScanner(os.Stdin)
var output strings.Builder
for scanner.Scan() {
output.WriteString(fmt.Sprintln(scanner.Text()))
}
if err := scanner.Err(); err != nil {
return "", err
}
return output.String(), nil
}
func getTemplate(templatePath string) (*template.Template, error) {
templateDir, templateFile := path.Split(templatePath)
funcs := template.FuncMap{
"include": includeFile(templateDir),
}
if templateFile != "" {
t, err := template.New(templateFile).Funcs(funcs).ParseFiles(templatePath)
return t, err
}
tmpl, err := readFromStdin()
t, err := template.New("stdin").Funcs(funcs).Parse(tmpl)
return t, err
}