-
Notifications
You must be signed in to change notification settings - Fork 2
/
servethis.go
53 lines (45 loc) · 1.08 KB
/
servethis.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
package main
import (
"log"
"net"
"net/http"
"os"
)
func main() {
cwd, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
listner, err := net.Listen("tcp4", ":0")
if err != nil {
log.Fatal(err)
}
_, port, err := net.SplitHostPort(listner.Addr().String())
if err != nil {
log.Fatal("Unable to parse listening port")
}
addrs, err := net.InterfaceAddrs()
if err != nil {
log.Fatal("Error retrieving interfaces")
}
ifaces := []string{}
for _, addr := range addrs {
ip, _, err := net.ParseCIDR(addr.String())
if err != nil || ip.To4() == nil || ip.IsLoopback() || ip.IsMulticast() {
continue
}
ifaces = append(ifaces, ip.String())
}
if len(ifaces) == 0 {
log.Fatal("No valid ipv4 interfaces found!")
}
log.Printf("Serving folder: %s Ctrl+C to exit", cwd)
for _, iface := range ifaces {
log.Printf("Listening on: http://%s:%s/", iface, port)
}
log.Fatal(http.Serve(listner, http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
log.Printf("Served %s to %s", r.URL, r.RemoteAddr)
http.FileServer(http.Dir(cwd)).ServeHTTP(w, r)
})))
}