Skip to content

Instantly share code, notes, and snippets.

@raugustinus
Created March 19, 2015 10:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raugustinus/f638d783c42c6e49a04e to your computer and use it in GitHub Desktop.
Save raugustinus/f638d783c42c6e49a04e to your computer and use it in GitHub Desktop.
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)
}
@raugustinus
Copy link
Author

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