Skip to content

Commit

Permalink
feat: add mime to httpx
Browse files Browse the repository at this point in the history
  • Loading branch information
katallaxie authored Jan 9, 2025
1 parent 54cd049 commit 1655243
Show file tree
Hide file tree
Showing 3 changed files with 92 additions and 0 deletions.
2 changes: 2 additions & 0 deletions httpx/doc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// Package httpx provides a set of utilities for working with the net/http package.
package httpx
48 changes: 48 additions & 0 deletions httpx/mime.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package httpx

import (
"errors"
"io"
"mime"
"net/http"
"path/filepath"

"github.com/zeiss/pkg/utilx"
)

// GetContentTypeByExtension returns the content type of a file based on its extension.
func GetContentTypeByExtension(file string) string {
ext := filepath.Ext(file)
switch ext {
case ".htm", ".html":
return "text/html"
case ".css":
return "text/css"
case ".js":
return "application/javascript"
default:
return mime.TypeByExtension(ext)
}
}

// GetContentType returns the content type of a file based on its extension.
func GetContentType(seeker io.ReadSeeker) (string, error) {
// At most the first 512 bytes of data are used:
// https://golang.org/src/net/http/sniff.go?s=646:688#L11
buff := make([]byte, 512)

_, err := seeker.Seek(0, io.SeekStart)
if err != nil {
return "", err
}

bytesRead, err := seeker.Read(buff)
if utilx.NotEmpty(err) && !errors.Is(err, io.EOF) {
return "", err
}

// Slice to remove fill-up zero values which cause a wrong content type detection in the next step
buff = buff[:bytesRead]

return http.DetectContentType(buff), nil
}
42 changes: 42 additions & 0 deletions httpx/mime_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package httpx

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestGetContentTypeByExtension(t *testing.T) {
tests := []struct {
name string
file string
expected string
}{
{
name: "html",
file: "index.html",
expected: "text/html",
},
{
name: "css",
file: "style.css",
expected: "text/css",
},
{
name: "js",
file: "script.js",
expected: "application/javascript",
},
{
name: "unknown",
file: "file",
expected: "",
},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
assert.Equal(t, test.expected, GetContentTypeByExtension(test.file))
})
}
}

0 comments on commit 1655243

Please sign in to comment.