github.com/greenpau/go-authcrunch@v1.1.4/pkg/util/file/utils.go (about) 1 // Copyright 2022 Paul Greenberg greenpau@outlook.com 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package file 16 17 import ( 18 "bufio" 19 "bytes" 20 "fmt" 21 "io/ioutil" 22 "os" 23 "path/filepath" 24 "strings" 25 ) 26 27 // ReadCertFile reads certificate files. 28 func ReadCertFile(filePath string) (string, error) { 29 var buffer bytes.Buffer 30 var RecordingEnabled bool 31 fileHandle, err := os.Open(filePath) 32 if err != nil { 33 return "", err 34 } 35 defer fileHandle.Close() 36 37 scanner := bufio.NewScanner(fileHandle) 38 for scanner.Scan() { 39 line := scanner.Text() 40 if strings.HasPrefix(line, "-----") { 41 if strings.Contains(line, "BEGIN CERTIFICATE") { 42 RecordingEnabled = true 43 continue 44 } 45 if strings.Contains(line, "END CERTIFICATE") { 46 break 47 } 48 } 49 if RecordingEnabled { 50 buffer.WriteString(strings.TrimSpace(line)) 51 } 52 } 53 54 if err := scanner.Err(); err != nil { 55 return "", err 56 } 57 58 return buffer.String(), nil 59 } 60 61 // ReadFile reads a file. 62 func ReadFile(filePath string) (string, error) { 63 var buffer bytes.Buffer 64 fileHandle, err := os.Open(filePath) 65 if err != nil { 66 return "", err 67 } 68 defer fileHandle.Close() 69 70 scanner := bufio.NewScanner(fileHandle) 71 for scanner.Scan() { 72 line := scanner.Text() 73 buffer.WriteString(strings.TrimSpace(line)) 74 } 75 76 if err := scanner.Err(); err != nil { 77 return "", err 78 } 79 80 return buffer.String(), nil 81 } 82 83 func expandHomePath(fp string) (string, error) { 84 if fp == "" { 85 return fp, fmt.Errorf("cannot expand an empty string") 86 } 87 if fp[0] != '~' { 88 return fp, nil 89 } 90 hd, err := os.UserHomeDir() 91 if err != nil { 92 return fp, err 93 } 94 fp = filepath.Join(hd, fp[1:]) 95 return fp, nil 96 } 97 98 // ReadFileBytes expands home directory and reads a file. 99 func ReadFileBytes(fp string) ([]byte, error) { 100 if fp == "" { 101 return nil, fmt.Errorf("cannot expand an empty string") 102 } 103 fp, err := expandHomePath(fp) 104 if err != nil { 105 return nil, err 106 } 107 return ioutil.ReadFile(fp) 108 } 109 110 // ExpandPath expands file system path. 111 func ExpandPath(s string) string { 112 p, err := expandHomePath(s) 113 if err != nil { 114 return s 115 } 116 return p 117 }