1 package sanitizers
2 3 import (
4 "fmt"
5 "net"
6 "os"
7 "os/user"
8 "path/filepath"
9 "strings"
10 )
11 12 const (
13 NetAddress = "netaddress"
14 Password = "password"
15 FilePath = "filepath"
16 Directory = "directory"
17 )
18 19 func StringType(typ, input string, defaultPort int) (cleaned string, e error) {
20 switch typ {
21 case NetAddress:
22 var h, p string
23 if h, p, e = net.SplitHostPort(input); E.Chk(e) {
24 e = fmt.Errorf("address value '%s' not a valid address", input)
25 return
26 }
27 if p == "" {
28 cleaned = net.JoinHostPort(h, fmt.Sprint(defaultPort))
29 }
30 case Password:
31 // password type is mainly here for the input method of the app using this config library
32 case FilePath:
33 if strings.HasPrefix(input, "~") {
34 var homeDir string
35 var usr *user.User
36 var e error
37 if usr, e = user.Current(); e == nil {
38 homeDir = usr.HomeDir
39 }
40 // Fall back to standard HOME environment variable that works for most POSIX OSes if the directory from the Go
41 // standard lib failed.
42 if e != nil || homeDir == "" {
43 homeDir = os.Getenv("HOME")
44 }
45 46 input = strings.Replace(input, "~", homeDir, 1)
47 }
48 if cleaned, e = filepath.Abs(filepath.Clean(input)); E.Chk(e) {
49 }
50 case Directory:
51 if strings.HasPrefix(input, "~") {
52 var homeDir string
53 var usr *user.User
54 var e error
55 if usr, e = user.Current(); e == nil {
56 homeDir = usr.HomeDir
57 }
58 // Fall back to standard HOME environment variable that works for most POSIX OSes if the directory from the Go
59 // standard lib failed.
60 if e != nil || homeDir == "" {
61 homeDir = os.Getenv("HOME")
62 }
63 64 input = strings.Replace(input, "~", homeDir, 1)
65 }
66 if cleaned, e = filepath.Abs(filepath.Clean(input)); E.Chk(e) {
67 }
68 default:
69 cleaned = input
70 }
71 return
72 }
73