about summary refs log tree commit diff
path: root/main.go
blob: e53c9596f2fa96d37d1467292cd2b258e3e57196 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package main

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

	"github.com/gorilla/mux"
)

func main() {

	// define the flags
	ip := flag.String("ip", "0.0.0.0", "ip to listen on")
	port := flag.String("p", "8087", "port to listen on")
	dir := flag.String("dir", "./", "path to host")
	flag.Parse()

	// define the router
	r := mux.NewRouter()
	r.Use(loggingMiddleware)

	// define the subrouter hosting the previously defined directory
	files := r.PathPrefix("/").Subrouter()
	fs := http.FileServer(http.Dir(*dir))
	files.PathPrefix("/").Handler(http.StripPrefix("/", fs))

	// define the http server using the values defined using flags
	httpServer := http.Server{
		Addr:    fmt.Sprintf("%s:%s", *ip, *port),
		Handler: r,
	}

	// start the http server
	log.Printf("http server listening on %s:%s hosting %s", *ip, *port, *dir)
	log.Fatal(httpServer.ListenAndServe())
}

func loggingMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		log.Println(r.RequestURI)
		next.ServeHTTP(w, r)
	})
}