I am using vite as build tool for my react app and golang as backend.
I built the app for production and host the app on my http server.
my directory structure:
JavaScript
x
8
1
server
2
|- dist
3
| | index.html
4
| |- assets
5
| | index.js
6
| | index.css
7
| main.go
8
To host my files the code looks like (inside main.go)
JavaScript
1
3
1
fs := http.FileServer(http.Dir("./dist"))
2
http.Handle("/", fs)
3
in index.html
JavaScript
1
3
1
<script type="module" crossorigin src="/assets/index.fd457ca0.js"></script>
2
<link rel="stylesheet" href="/assets/index.bdcfd918.css">
3
The code did actually send correct files but with wrong headers.
Advertisement
Answer
So I had to write my own file server to set the headers manually like:
JavaScript
1
31
31
1
contentTypeMap := map[string]string{
2
".html": "text/html",
3
".css": "text/css",
4
".js": "application/javascript",
5
}
6
7
filepath.Walk("./dist", func(path string, info os.FileInfo, err error) error {
8
if err != nil {
9
log.Fatalf(err.Error())
10
}
11
if info.IsDir() {
12
return err
13
}
14
15
dirPath := filepath.ToSlash(filepath.Dir(path))
16
contentType := contentTypeMap[filepath.Ext(info.Name())]
17
handlePath := "/" + strings.Join(strings.Split(dirPath, "/")[1:], "/")
18
19
hf := func(w http.ResponseWriter, r *http.Request) {
20
w.Header().Add("Content-Type", contentType) // <---- key part
21
http.ServeFile(w, r, path)
22
}
23
24
if handlePath != "/" {
25
handlePath += "/" + info.Name()
26
}
27
28
mainRouter.HandleFunc(handlePath, hf)
29
return nil
30
})
31
(please optimize if the code is bad, I made the solution myself and I tried so many stuff to fit my needs)
Now with that I recevied the correct files with correct headers.
And I couldn’t find any solutions to work with custom headers using http.FileServer
in http package. And please provide a easy solution if it exists.