Skip to content

Instantly share code, notes, and snippets.

@stever
Last active June 18, 2023 12:55
Show Gist options
  • Save stever/8d3df4cab352189114f0 to your computer and use it in GitHub Desktop.
Save stever/8d3df4cab352189114f0 to your computer and use it in GitHub Desktop.
Go serve files over HTTP. Useful for testing a HTML web application.
package main
import (
"log"
"mime"
"net/http"
"path/filepath"
)
func main() {
addr := ":8081"
path := "."
log.Printf("Server starting on %s", addr)
mime.AddExtensionType(".svg", "image/svg+xml")
mime.AddExtensionType(".json", "application/json")
mime.AddExtensionType(".xslt", "text/xsl")
htdocs, _ := filepath.Abs(path)
fs := http.FileServer(http.Dir(htdocs))
http.Handle("/", cors(fs))
http.ListenAndServe(addr, nil)
}
func cors(fs http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Access-Control-Allow-Origin", "*")
w.Header().Add("Access-Control-Allow-Credentials", "true")
w.Header().Add("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
w.Header().Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
if r.Method == "OPTIONS" {
http.Error(w, "No Content", http.StatusNoContent)
return
}
fs.ServeHTTP(w, r)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment