Skip to content

Instantly share code, notes, and snippets.

@eginez
Last active June 10, 2017 21:36
Show Gist options
  • Save eginez/ae98527eb0fa23fe39e47535b517e53c to your computer and use it in GitHub Desktop.
Save eginez/ae98527eb0fa23fe39e47535b517e53c to your computer and use it in GitHub Desktop.
Provides a simple web server (a la python SimpleHttpServer)
// Provides a simple web server (a la python SimpleHttpServer) that will serve from
// the current location or from an argument passed in as parameter
// it requires the port as parameter
package main
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"os"
"os/exec"
"path"
"strings"
)
func pwd() string {
cmd := exec.Command("pwd")
output, _ := cmd.Output()
return string(output)
}
func serveDir(req *http.Request, dir string) []byte {
var buff bytes.Buffer
files, _ := ioutil.ReadDir(dir)
buff.WriteString("<html><body><ul>")
for _, f := range files {
s := fmt.Sprintf("<li><a href=%s>%s</a></li>",
path.Join(req.URL.Path, f.Name()),
f.Name())
buff.WriteString(s)
}
buff.WriteString("</ul></body></html>")
return buff.Bytes()
}
func serveFile(filePath string) []byte {
b, _ := ioutil.ReadFile(filePath)
return b
}
func fsHandler(root string) http.Handler {
fn := func(w http.ResponseWriter, req *http.Request) {
currPath := path.Join(root, req.URL.Path)
info, err := os.Stat(currPath)
if err != nil {
w.Write([]byte("error"))
return
}
if info.IsDir() {
w.Write(serveDir(req, currPath))
} else {
w.Header().Add("Content-Type", "plain/text")
w.Write(serveFile(currPath))
}
}
return http.HandlerFunc(fn)
}
func main() {
args := os.Args[1:]
port := args[0]
var root string
if len(args) > 1 {
root = args[1]
} else {
root = strings.TrimSpace(pwd())
}
mux := http.NewServeMux()
mux.Handle("/", fsHandler(root))
fmt.Println(fmt.Sprintf("Listening to %s, serving from %s", port, root))
http.ListenAndServe(fmt.Sprintf(":%s", port), mux)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment