Skip to content

impr: Switch to h2non/filetype #12

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 6 additions & 27 deletions fileutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,16 @@ package main
import (
"bufio"
"encoding/json"
"github.com/h2non/filetype"
"io/fs"
"log"
"net/http"
"os"
"path/filepath"
)

func ReadFileUnsafe(file string, removeNewline bool) string {
content, err := ReadFile(file)
b, err := os.ReadFile(file)
content := string(b)

if err != nil {
log.Printf("- Failed to read '%s'", file)
Expand All @@ -28,11 +29,6 @@ func ReadFileUnsafe(file string, removeNewline bool) string {
return content
}

func ReadFile(file string) (string, error) {
dat, err := os.ReadFile(file)
return string(dat), err
}

func ReadUserTokens() map[string]UserToken {
dat, err := os.ReadFile("user_tokens.json")
if err != nil {
Expand Down Expand Up @@ -72,7 +68,7 @@ func IsDirectory(path string) (bool, error) {
}
}

func GetFileContentTypeExt(out *os.File, file string) (string, error) {
func GetFileContentTypeExt(content []byte, file string) (string, error) {
ext := filepath.Ext(file)

switch ext {
Expand All @@ -90,25 +86,8 @@ func GetFileContentTypeExt(out *os.File, file string) (string, error) {
return "application/json; charset=utf-8", nil
}

return GetFileContentType(out)
}

// GetFileContentType detects the content type
// and returns a valid MIME type
func GetFileContentType(out *os.File) (string, error) {
// Only the first 512 bytes are used to sniff the content type.
buffer := make([]byte, 512)

_, err := out.Read(buffer)
if err != nil {
return "", err
}

// Use the net/http package's handy DetectContentType function. Always returns a valid
// content-type by returning "application/octet-stream" if no others seemed to match.
contentType := http.DetectContentType(buffer)

return contentType, nil
kind, err := filetype.Match(content)
return kind.MIME.Type, err
}

// ReadLines reads a whole file into memory
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ go 1.17

require (
github.com/ferluci/fast-realip v1.0.1
github.com/h2non/filetype v1.1.3
github.com/valyala/fasthttp v1.50.0
)

Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ github.com/andybalholm/brotli v1.0.6 h1:Yf9fFpf49Zrxb9NlQaluyE92/+X7UVHlhMNJN2sx
github.com/andybalholm/brotli v1.0.6/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
github.com/ferluci/fast-realip v1.0.1 h1:zPi0iv7zgOOlM/qJt9mozLz5IjVRAezaqHJoQ0JJ/yI=
github.com/ferluci/fast-realip v1.0.1/go.mod h1:Ag7xdRQ9GOCL/pwbDe4zJv6SlfYdROArc8O+qIKhRc4=
github.com/h2non/filetype v1.1.3 h1:FKkx9QbD7HR/zjK1Ia5XiBsq9zdLi5Kf3zGyFTAFkGg=
github.com/h2non/filetype v1.1.3/go.mod h1:319b3zT68BvV+WRj7cwy856M2ehB3HqNOt6sy1HndBY=
github.com/klauspost/compress v1.8.2/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A=
github.com/klauspost/compress v1.16.3/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE=
github.com/klauspost/compress v1.17.1 h1:NE3C767s2ak2bweCZo3+rdP4U/HoyVXLv/X9f2gPS5g=
Expand Down
29 changes: 13 additions & 16 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -308,37 +308,33 @@ func HandleServeFile(ctx *fasthttp.RequestCtx, path string, public bool) {
return
}

content, err := ReadFile(path)
content, err := os.ReadFile(path)
if err != nil {
HandleInternalServerError(ctx, err)
return
}

// File is empty
if len(content) == 0 {
ctx.Response.SetStatusCode(fasthttp.StatusNoContent)
return
}

if err != nil {
HandleInternalServerError(ctx, err)
return
}
kind, err := GetFileContentTypeExt(content, path)

// Open the file and handle errors
f, err := os.Open(path)
if err != nil {
HandleInternalServerError(ctx, err)
return
}
defer f.Close()

// Get the contentType
contentType, err := GetFileContentTypeExt(f, path)
if err != nil {
HandleInternalServerError(ctx, err)
if len(kind) == 0 {
HandleGeneric(ctx, fasthttp.StatusInternalServerError, "Unknown file type")
return
}

// Serve the file itself
ctx.Response.Header.Set(fasthttp.HeaderContentType, contentType)
fmt.Fprint(ctx, content)
ctx.Response.Header.Set(fasthttp.HeaderContentType, kind)
fmt.Fprint(ctx, string(content))
}

func HandleAppendFile(ctx *fasthttp.RequestCtx, path string) {
Expand All @@ -355,10 +351,11 @@ func HandleAppendFile(ctx *fasthttp.RequestCtx, path string) {
}

contentStr := string(content) + "\n"
oldContent, err := ReadFile(path)
oldContent, err := os.ReadFile(path)

// Append to old content only if the file didn't error, otherwise we just write to the file directly
if err == nil {
contentStr = oldContent + contentStr
contentStr = string(oldContent) + contentStr
}

err = WriteToFile(path, contentStr)
Expand Down