Skip to content

Instantly share code, notes, and snippets.

@srikumarks
Created October 1, 2012 04:50
Show Gist options
  • Save srikumarks/3809524 to your computer and use it in GitHub Desktop.
Save srikumarks/3809524 to your computer and use it in GitHub Desktop.
A simple local file server written in Go
// This code is hereby placed in the PUBLIC DOMAIN.
package main
import "fmt"
import "net/http"
import "os"
// A very simple go local file server.
// 1. Serves on port 8000
// 2. Serves files relative to the directory in which you run the server.
//
// Compile using "go build webview.go".
//
// This works better than python's SimpleHTTPServer because this go version
// can handle partial file requests, which are needed today for html5
// audio and video items.
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// Make path relative to current directory.
path := "." + r.URL.Path
// If the path refers to a directory and no '/' has been given,
// then redirect to a path containing '/' so that the browser will
// generate correct URL requests for relative paths in HTML files.
dir, _ := os.Stat(path)
if dir != nil {
if dir.IsDir() && path[len(path)-1] != '/' {
http.Redirect(w, r, r.URL.Path+"/", 301)
return
}
}
// Serve the path. Go's server automatically pulls index.html
// files in directories.
http.ServeFile(w, r, path)
// Show the path being served on the console for diagnostic purposes.
fmt.Println(path)
})
http.ListenAndServe(":8000", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment