randomLine take a random line from a file
(filePath string)
| 3751 | |
| 3752 | // randomLine take a random line from a file |
| 3753 | func randomLine(filePath string) (string, error) { |
| 3754 | file, err := os.Open(filePath) |
| 3755 | if err != nil { |
| 3756 | return "", err |
| 3757 | } |
| 3758 | defer func(file *os.File) { |
| 3759 | _ = file.Close() |
| 3760 | }(file) |
| 3761 | |
| 3762 | var lines []string |
| 3763 | scanner := bufio.NewScanner(file) |
| 3764 | for scanner.Scan() { |
| 3765 | line := strings.TrimRight(scanner.Text(), "\r") |
| 3766 | if line == "" { |
| 3767 | continue |
| 3768 | } |
| 3769 | lines = append(lines, line) |
| 3770 | } |
| 3771 | |
| 3772 | if err := scanner.Err(); err != nil { |
| 3773 | return "", err |
| 3774 | } |
| 3775 | |
| 3776 | if len(lines) == 0 { |
| 3777 | return "", fmt.Errorf("no entries found in %s", filePath) |
| 3778 | } |
| 3779 | |
| 3780 | // Select a random Line |
| 3781 | randomLine := lines[rand.Intn(len(lines))] |
| 3782 | |
| 3783 | return randomLine, nil |
| 3784 | } |
| 3785 | |
| 3786 | // joinURL safely joins a base URL and a path, preserving slashes |
| 3787 | func joinURL(base string, path string) string { |
no outgoing calls
no test coverage detected