-
Notifications
You must be signed in to change notification settings - Fork 60
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Move contenttype checks to util package
- Loading branch information
1 parent
328452b
commit 2ccf795
Showing
2 changed files
with
39 additions
and
33 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
package util | ||
|
||
import ( | ||
"fmt" | ||
"net/http" | ||
"os" | ||
"strings" | ||
) | ||
|
||
func detectContentType(file *os.File) (string, error) { | ||
// Only the first 512 bytes are used to sniff the content type. | ||
buffer := make([]byte, 512) | ||
n, err := file.Read(buffer) | ||
// Reset the file so a scanner can scan | ||
_, _ = file.Seek(0, 0) | ||
|
||
if err != nil { | ||
return "", err | ||
} | ||
return http.DetectContentType(buffer[:n]), nil | ||
} | ||
|
||
func isTextFile(file *os.File) bool { | ||
contentType, err := detectContentType(file) | ||
if err != nil { | ||
return false | ||
} | ||
|
||
return strings.HasPrefix(contentType, "text/plain") | ||
} | ||
|
||
func IsTextFile(file *os.File) error { | ||
if !isTextFile(file) { | ||
return fmt.Errorf("%s is not a text file", file.Name()) | ||
} | ||
return nil | ||
} |