Skip to content

Instantly share code, notes, and snippets.

@gorakhargosh
Created November 25, 2015 00:15
Show Gist options
  • Select an option

  • Save gorakhargosh/7bab8be451205ba21b08 to your computer and use it in GitHub Desktop.

Select an option

Save gorakhargosh/7bab8be451205ba21b08 to your computer and use it in GitHub Desktop.

Revisions

  1. gorakhargosh created this gist Nov 25, 2015.
    43 changes: 43 additions & 0 deletions serve.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    // A static file server written in Go.

    package main

    import (
    "flag"
    "fmt"
    "log"
    "net/http"
    "os"
    )

    type Options struct {
    // The port on which the server should listen.
    Port int

    // The address on which the server should listen.
    Host string
    }

    func main() {
    var options Options

    flag.IntVar(&options.Port, "port", 3000, "the port on which to listen")
    flag.StringVar(&options.Host, "host", "localhost", "the host on which to listen")
    flag.Parse()

    var dir string
    var err error
    if len(flag.Args()) > 0 {
    dir = flag.Arg(0)
    } else {
    dir, err = os.Getwd()
    if err != nil {
    log.Fatal("cannot determine current working directory")
    }
    }

    fs := http.FileServer(http.Dir(dir))
    http.Handle("/", fs)
    log.Printf("Listening on %s:%d...\n", options.Host, options.Port)
    http.ListenAndServe(fmt.Sprintf(":%d", options.Port), nil)
    }