-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
67 lines (59 loc) · 1.52 KB
/
main.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package main
import (
"flag"
"fmt"
"io"
"net/url"
"os"
"strings"
)
var version string = "--"
// ======================================================
func main() {
// declare flags
input := flag.String("input", "", "string to escape, if empty (default) read from stdin")
keepSpaces := flag.Bool("keep-spaces", false, "keep spaces as they are")
usePathEscape := flag.Bool("path-escape", false, "use PathEscape instead of QueryEscape")
trimSpaces := flag.Bool("trim", false, "trim (from both sides) whitespaces and newlines")
// set os.Stdout as the default output for the flag package
flag.CommandLine.SetOutput(os.Stdout)
// Help message
flag.Usage = func() {
fmt.Printf("urlencode (version: %s)\n\n", version)
fmt.Printf("This program is a thin wrapper around the standard go url escape functions.\nAvailable flags:\n\n")
flag.PrintDefaults()
fmt.Println("")
}
// parse flags
flag.Parse()
// recover input string
str := string(*input)
// if it is empty read the text from stdin
if *input == "" {
data, err := io.ReadAll(os.Stdin)
if err != nil {
os.Exit(1)
}
str = string(data)
}
// trim spaces and new lines if needed
if *trimSpaces {
str = strings.Trim(str, " \n\r")
}
// escape data
if *usePathEscape {
str = url.PathEscape(str)
} else {
str = url.QueryEscape(str)
}
// recover spaces if needed
if *keepSpaces {
space := "+"
if *usePathEscape {
space = "%20"
}
str = strings.ReplaceAll(str, space, " ")
}
// write escaped string to stdout
os.Stdout.Write([]byte(str))
}