Skip to content

Instantly share code, notes, and snippets.

@imjasonh
Last active October 28, 2021 06:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save imjasonh/c8e09f4ab1721467b162 to your computer and use it in GitHub Desktop.
Save imjasonh/c8e09f4ab1721467b162 to your computer and use it in GitHub Desktop.
package main
import (
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"path"
)
var (
dir = flag.String("dir", "", "Root directory to serve")
port = flag.Int("port", 8080, "Port to serve on")
readonly = flag.Bool("readonly", false, "If true, only read operations will be supported")
)
func main() {
flag.Parse()
if *readonly {
http.Handle("/", http.FileServer(http.Dir(*dir)))
} else {
http.Handle("/", http.StripPrefix("/", http.HandlerFunc(handler)))
}
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", *port), nil))
}
func handler(w http.ResponseWriter, r *http.Request) {
path := path.Join(*dir, r.URL.Path)
switch r.Method {
case "GET":
log.Printf("serving %s", path)
f, err := os.Open(path)
if err != nil {
handleError(w, err)
return
}
defer f.Close()
io.Copy(w, f)
case "DELETE":
log.Printf("deleting %s", path)
if err := os.Remove(path); err != nil {
handleError(w, err)
return
}
case "PUT", "POST":
log.Printf("updating %s", path)
f, err := os.Create(path)
if err != nil {
handleError(w, err)
return
}
defer f.Close()
defer r.Body.Close()
io.Copy(f, r.Body)
case "HEAD":
fi, err := os.Stat(path)
if err != nil {
handleError(w, err)
return
}
w.Header().Set("Content-length", fmt.Sprintf("%d", fi.Size()))
default:
http.Error(w, r.Method+" not supported", http.StatusMethodNotAllowed)
}
}
func handleError(w http.ResponseWriter, err error) {
switch err {
case os.ErrPermission:
http.Error(w, err.Error(), http.StatusForbidden)
case os.ErrNotExist:
http.Error(w, err.Error(), http.StatusNotFound)
default:
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment