-
Notifications
You must be signed in to change notification settings - Fork 4
/
http.server.go
79 lines (69 loc) · 1.81 KB
/
http.server.go
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package main
import (
"flag"
"fmt"
"log"
"net/http"
"reflect"
"strings"
"github.com/ac0d3r/nicu/pkg/network"
)
var (
flagHelp = flag.Bool("h", false, "Shows usage options.")
flagHost = flag.String("l", ":8080", "listen host")
flagDir = flag.String("d", "./", "load directory")
flagFile = flag.String("f", "", "load single file")
)
func banner() {
t := `
__ __ __
/ / / /_/ /____ ___ ___ _____ _____ ____
/ _ \/ __/ __/ _ \_ (_-</ -_) __/ |/ / -_) __/
/_//_/\__/\__/ .__(_)___/\__/_/ |___/\__/_/
/_/
`
fmt.Println(t)
}
func getStatusCode(w http.ResponseWriter) int64 {
respValue := reflect.ValueOf(w)
if respValue.Kind() == reflect.Ptr {
respValue = respValue.Elem()
}
status := respValue.FieldByName("status")
return status.Int()
}
func withlog(h http.Handler) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h.ServeHTTP(w, r)
log.Printf("handle %s %d\n", r.URL.Path, getStatusCode(w))
})
}
func main() {
banner()
flag.Parse()
if *flagHelp {
fmt.Printf("Usage: http.server [options]\n\n")
flag.PrintDefaults()
return
}
if len(strings.Split(*flagHost, ":")[0]) == 0 {
fmt.Printf("listen on http://localhost%s\n", *flagHost)
if ipnets, err := network.GetLocalIPV4Net(); err == nil && len(ipnets) >= 1 {
fmt.Printf("listen on http://%s%s\n", ipnets[0].IP, *flagHost)
}
} else {
fmt.Printf("listen on http://%s\n", *flagHost)
}
var handler http.Handler
if *flagFile != "" {
handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, *flagFile)
})
} else {
if *flagDir == "" {
*flagDir = "./"
}
handler = http.FileServer(http.Dir(*flagDir))
}
log.Fatal(http.ListenAndServe(*flagHost, withlog(handler)))
}