Created
August 19, 2015 20:31
-
-
Save EtienneR/9712a181d5501ca4f545 to your computer and use it in GitHub Desktop.
Display files in a folder and then, display file content
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io/ioutil" | |
"path/filepath" | |
) | |
type FileInfo struct { | |
Name string | |
} | |
func main() { | |
// Get files present in the "tmp" directory | |
entries, err := ioutil.ReadDir("tmp/") | |
if err != nil { | |
fmt.Println(err) | |
} | |
// Display in a loop, on name file | |
for _, entry := range entries { | |
f := FileInfo{ | |
Name: entry.Name(), | |
} | |
fmt.Println(". " + f.Name) | |
} | |
var filename string | |
fmt.Println("Enter filename ") | |
fmt.Scanf("%s", &filename) | |
file := "tmp/" + filename | |
// Get extension | |
extension := filepath.Ext(file) | |
// Accepted extensions | |
if extension == ".html" || extension == ".txt" { | |
// Read file | |
file, err := ioutil.ReadFile(file) | |
if err != nil { | |
fmt.Println(err) | |
} | |
// Display file content | |
fmt.Println(string(file)) // convert byte to string | |
} else { | |
fmt.Println("Extension '" + extension + "', not accepted") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment