Last active
November 21, 2024 15:11
-
-
Save paulmach/7271283 to your computer and use it in GitHub Desktop.
Simple Static File Server in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Serve is a very simple static file server in go | |
Usage: | |
-p="8100": port to serve on | |
-d=".": the directory of static files to host | |
Navigating to http://localhost:8100 will display the index.html or directory | |
listing file. | |
*/ | |
package main | |
import ( | |
"flag" | |
"log" | |
"net/http" | |
) | |
func main() { | |
port := flag.String("p", "8100", "port to serve on") | |
directory := flag.String("d", ".", "the directory of static file to host") | |
flag.Parse() | |
http.Handle("/", http.FileServer(http.Dir(*directory))) | |
log.Printf("Serving %s on HTTP port: %s\n", *directory, *port) | |
log.Fatal(http.ListenAndServe(":"+*port, nil)) | |
} |
Thanks a lot, This is great! @paulmach
Thanks!
Does anybody happen to know why browsers try to display the old directory listing, even though the server is now launched from a different directory?
It's the same on my firefox on Linux machine and chrome on my android. If I reopen the page it'll show the old listing, even though it gets 404 if files are accessed. If I open in incognito or new browser, everything is fine and the new listing is loaded.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
example for cors, need to adjust for your need (cache, implementation)
package main
import "net/http"
func addCORS(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Cross-Origin-Embedder-Policy", "require-corp")
w.Header().Set("Cross-Origin-Opener-Policy", "same-origin")
next.ServeHTTP(w, req)
})
}
func main() {
port := ":9999"
handler := addCORS(http.FileServer(http.Dir("files")))
http.ListenAndServe(port, handler)
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks!
Does anybody happen to know why browsers try to display the old directory listing, even though the server is now launched from a different directory?
It's the same on my firefox on Linux machine and chrome on my android. If I reopen the page it'll show the old listing, even though it gets 404 if files are accessed. If I open in incognito or new browser, everything is fine and the new listing is loaded.