Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple Static File Server in Go
/*
Serve is a very simple static file server in go
Usage:
-p="8100": port to serve on
-d=".": the directory of static files to host
Navigating to http://localhost:8100 will display the index.html or directory
listing file.
*/
package main
import (
"flag"
"log"
"net/http"
)
func main() {
port := flag.String("p", "8100", "port to serve on")
directory := flag.String("d", ".", "the directory of static file to host")
flag.Parse()
http.Handle("/", http.FileServer(http.Dir(*directory)))
log.Printf("Serving %s on HTTP port: %s\n", *directory, *port)
log.Fatal(http.ListenAndServe(":"+*port, nil))
}
@philippgille
Copy link

philippgille commented May 15, 2018

@paulmach Thanks a lot!

@95rade
Copy link

95rade commented Oct 24, 2018

Awesome example of a simplest go web service. thanks for sharing

@bryaakov
Copy link

bryaakov commented Oct 30, 2018

👍

@OnTitansShoulder
Copy link

OnTitansShoulder commented Apr 19, 2021

Thanks for sharing, this is neat.

@immartian
Copy link

immartian commented Apr 9, 2022

@abiiranathan
Copy link

abiiranathan commented Apr 12, 2022

It's weird that this exists. I was tired of using python3 -m http.server and decided to create my own. After, I googled to see what's out there, and alas!!

package main

import (
	"flag"
	"log"
	"net/http"
	"path/filepath"
)

var (
	path = flag.String("path", ".", "path to the folder to serve. Defaults to the current folder")
	port = flag.String("port", "8080", "port to serve on. Defaults to 8080")
)

func main() {
	flag.Parse()

	dirname, err := filepath.Abs(*path)
	if err != nil {
		log.Fatalf("Could not get absolute path to directory: %s: %s", dirname, err.Error())
	}

	log.Printf("Serving %s on port %s", dirname, *port)

	err = Serve(dirname, *port)
	if err != nil {
		log.Fatalf("Could not serve directory: %s: %s", dirname, err.Error())
	}

}

func Serve(dirname string, port string) error {
	fs := http.FileServer(http.Dir(dirname))
	http.Handle("/", fs)

	return http.ListenAndServe(":"+port, nil)
}

@kfelter
Copy link

kfelter commented May 10, 2022

Thanks!

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