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 (
func handler(w http.ResponseWriter, req *http.Request, path string) {
data, err := ioutil.ReadFile(path)
w.Header().Set("Content-Type", "text/html")
fmt.Fprintf(w, "%s", data)
func check(e error) {
if e != nil {
fmt.Printf("error: %s", e)
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)
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 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