package main
import
(
"flag"
"fmt"
"log"
"net/http"
"os"
"strconv"
"strings"
)
func exist(filename string)
bool
{
_, err :
=
os.Stat(filename)
return
err
=
=
nil || !os.IsNotExist(err)
}
func serveFiles(h http.Handler, listDir
bool
, basedir string) http.HandlerFunc {
return
http.HandlerFunc(func(w http.ResponseWriter, r
*
http.Request) {
const indexpage
=
"index.html"
log.Println(r.URL.Path)
if
strings.HasSuffix(r.URL.Path,
"/"
) {
indexpath :
=
basedir
+
indexpage
if
exist(indexpath) {
http.ServeFile(w, r, indexpath)
return
}
if
!listDir {
http.NotFound(w, r)
return
}
}
h.ServeHTTP(w, r)
})
}
func main() {
port :
=
80
listDir :
=
false
httpdir :
=
"./http_dir/"
flag.IntVar(&port,
"p"
,
80
,
"listen port"
)
flag.BoolVar(&listDir,
"l"
, false,
"list directory"
)
flag.StringVar(&httpdir,
"d"
,
"./http_dir/"
,
"http directory"
)
flag.Parse()
if
port <
1
|| port >
65535
{
fmt.Println(
"invalid port (1-65535)"
)
return
}
if
!exist(httpdir) {
fmt.Println(
"invalid path"
)
return
}
log.Println(
"httpserver listen on "
+
strconv.Itoa(port))
http.Handle(
"/"
, serveFiles(http.FileServer(http.
Dir
(httpdir)), listDir, httpdir))
log.Println(http.ListenAndServe(
":"
+
strconv.Itoa(port), nil))
}