I am new to golang and i am trying to make a server which will fetch the list of files and create an html and write it to the response
i have created links of the file so that when it is clicked , then the file is downloaded
But this is not happening , instead the html is being downloaded instead of file
here is what i am doing
package main
import (
"fmt"
"io/ioutil"
"net/http"
"io"
)
func getFile(res http.ResponseWriter, req *http.Request) {
files, _ := ioutil.ReadDir("./publicFolder/")
res.Header().Set("Content-Type", "text/html; charset=utf-8")
myHtml := `
<!DOCTYPE html>
<html>
<head>
<title>Home Network</title>
</head>
<body>
<ul>`
for _, f := range files {
fmt.Println(f.Name())
myHtml += (`
<a href="./publicFolder/` + f.Name() + `" download="`+f.Name()+`" >` + f.Name() + `</a>`)
}
myHtml += (
`
</ul>
</body>
</html>
`)
io.WriteString(res, myHtml)
}
func main() {
http.HandleFunc("/getFile/", getFile)
http.ListenAndServe(":8008", nil)
}
i have added download attribute to the html in tag But the html is being downloaded instead of file
i tried creating an html file and running it , in that case the file is being downloaded
here is the html which i created to test
<html>
<head>
</head>
<body>
<ul>
<li><a href="./publicFolder/doc.txt" download="doc.txt">file1</a></li>
</ul>
</body>
</html>
EDIT
the content of doc.txt when downloading using the golang server
<html>
<head>
<title>
Home Network
</title>
</head>
<body>
<ul>
<li>
<a href="./publicFolder/GAMES.cpp" download="GAMES.cpp">GAMES.cpp</a>
</li>
<li>
<a href="./publicFolder/doc.txt" download="doc.txt">doc.txt</a>
</li>
<li>
<a href="./publicFolder/erlang" download="erlang">erlang</a>
</li>
</ul>
</body>
</html>
Content of doc.txt when downloading from html file(and this is the actual content )
this is a test file doct.txt
EDIT i have added this FileServer
http.Handle("/getFile/publicFolder/", http.StripPrefix("/getFile/publicFolder/", http.FileServer(http.Dir("/publicFolder"))))