Created
March 31, 2018 12:07
-
-
Save feedbee/82b778b411f89c0514fa07423620c48b to your computer and use it in GitHub Desktop.
Simple static files web server written in golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
import "net/http" | |
import "flag" | |
import "os" | |
import "path/filepath" | |
func main() { | |
// --help | |
flag.Usage = func() { | |
_, filename := filepath.Split(os.Args[0]) | |
fmt.Printf("Simple webserver for serving static files from a file system\n") | |
fmt.Printf("Usage: %s -p=port_number directory\n", filename) | |
flag.PrintDefaults() | |
fmt.Printf("If the directory is not provided, workdir is served\n") | |
} | |
// Run quiet? | |
var quiet bool | |
flag.BoolVar(&quiet, "q", false, "Don't print initial message. Default is to print it.") | |
// Define port | |
var port int | |
flag.IntVar(&port, "p", 8000, "The port number to bind on. Default is 8000.") | |
flag.Parse() | |
// Define path | |
var path string | |
if (len(os.Args) > 1) { // serve provided path | |
path = os.Args[1] | |
} else { // serve the workdir | |
dir, err := os.Getwd() | |
if err != nil { | |
fmt.Printf("Error can't get workdir to serve\n") | |
os.Exit(2) | |
} | |
path = dir | |
} | |
// Run webserver | |
if (!quiet) { | |
fmt.Printf("Serving on port %d, workdir %s\n", port, path) | |
} | |
panic(http.ListenAndServe(fmt.Sprintf(":%d", port), http.FileServer(http.Dir(path)))) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment