Skip to content

Instantly share code, notes, and snippets.

@abiiranathan
Created April 12, 2022 09:48
Show Gist options
  • Save abiiranathan/6634b438a6ddd1c86dc94f13941c95e7 to your computer and use it in GitHub Desktop.
Save abiiranathan/6634b438a6ddd1c86dc94f13941c95e7 to your computer and use it in GitHub Desktop.
A file server written in go
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)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment