go-playground/cmd/playground/main.go

82 lines
1.4 KiB
Go
Raw Normal View History

package main
import (
"context"
"errors"
"fmt"
"io"
"os"
"git.jojodev.com/golang/go-playground"
)
func main() {
contents, err := readStdin()
if err != nil {
fmt.Println(err)
return
}
if contents == "" {
contents, err = readFile()
if err != nil {
fmt.Println(err)
return
}
}
if contents == "" {
fmt.Println("did not receive any data from stdin or a file")
return
}
code, err := playground.Share(context.Background(), contents)
if err != nil {
fmt.Printf("could not get share URL: %v\n", err)
return
}
fmt.Println(code.URL())
}
func readStdin() (string, error) {
fi, err := os.Stdin.Stat()
if err != nil {
return "", fmt.Errorf("could not stat stdin: %v", err)
}
if fi.Mode()&os.ModeNamedPipe != 0 {
contents, err := io.ReadAll(os.Stdin)
if err != nil {
return "", fmt.Errorf("could not read from stdin: %w", err)
}
return string(contents), nil
}
return "", nil
}
func readFile() (string, error) {
if len(os.Args) == 1 {
return "", nil
}
path := os.Args[1]
fi, err := os.Stat(path)
if err != nil {
return "", fmt.Errorf("could not stat %s: %v", path, err)
}
if fi.IsDir() {
return "", errors.New("can not share a directory")
}
if fi.Size() > 500000 {
return "", errors.New("this library limits the share payload to ~500kb")
}
contents, err := os.ReadFile(path)
if err != nil {
return "", fmt.Errorf("could not read file at %s: %w", path, err)
}
return string(contents), nil
}