Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
simple http serve util to serve a single static file on a port
package main
import (
"os"
"fmt"
"net/http"
"io/ioutil"
)
func handler(w http.ResponseWriter, req *http.Request, path string) {
data, err := ioutil.ReadFile(path)
check(err)
w.Header().Set("Content-Type", "text/html")
fmt.Fprintf(w, "%s", data)
}
func check(e error) {
if e != nil {
fmt.Printf("error: %s", e)
os.Exit(2)
}
}
func main() {
port := os.Args[1]
file := os.Args[2]
if _, err := os.Stat(file); os.IsNotExist(err) {
fmt.Printf("no such file or directory: %s\n", file)
os.Exit(1)
}
fmt.Printf("Serving %s on http://localhost:%s\n", file, port)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
handler(w, r, file)
})
http.ListenAndServe(":"+port, nil)
}
Owner

raugustinus commented Mar 19, 2015

while learning go I needed a simple way to serve a static file over http. Instead of running a webserver like apache or nginx with configuration etc. I just wanted something the easiest solution to host a single file on a specified port.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment