Skip to content

Instantly share code, notes, and snippets.

@akramsaouri
Created January 13, 2018 13:15
Show Gist options
  • Save akramsaouri/dcb20cc3b8ccc8d19ebbc36f92af22e2 to your computer and use it in GitHub Desktop.
Save akramsaouri/dcb20cc3b8ccc8d19ebbc36f92af22e2 to your computer and use it in GitHub Desktop.
Serve static files from your current directory.
package main
import (
"html/template"
"log"
"net/http"
"os"
"path/filepath"
)
const tpl = `
<html>
<head>
<title> file server </title>
</head>
<body>
<ul>
{{range .}}
<li> <a href="{{ . }}"> {{ . }} </a> </li>
{{end}}
</ul>
</body>
</html>
`
func main() {
sm := http.NewServeMux()
t, err := template.New("root").Parse(tpl)
if err != nil {
log.Fatal(err)
}
err = filepath.Walk(".", func(p string, fi os.FileInfo, err error) error {
pattern := "/"
if p != "." {
pattern = pattern + p
}
if fi.IsDir() {
file, err := os.Open(p)
if err != nil {
return err
}
defer file.Close()
names, err := file.Readdirnames(-1)
if err != nil {
return err
}
var hasIndex bool
files := make([]string, len(names))
for i, n := range names {
if n == "index.html" {
hasIndex = true
}
if p != "." {
files[i] = p + "/" + n
} else {
files[i] = n
}
}
if hasIndex {
sm.HandleFunc(pattern, func(res http.ResponseWriter, req *http.Request) {
http.ServeFile(res, req, p)
})
} else {
sm.HandleFunc(pattern, func(res http.ResponseWriter, req *http.Request) {
err = t.Execute(res, files)
if err != nil {
log.Fatal(err)
}
})
}
} else {
sm.HandleFunc(pattern, func(res http.ResponseWriter, req *http.Request) {
http.ServeFile(res, req, p)
})
}
return nil
})
if err != nil {
log.Fatal(err)
}
http.ListenAndServe(":9000", sm)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment