Created
July 1, 2020 11:46
-
-
Save kudarap/590b725fabecb4324f10f5ebca3d29d2 to your computer and use it in GitHub Desktop.
file serving though local netowk
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"fmt" | |
"os" | |
"net" | |
"net/http" | |
) | |
const defaultPort = 8000 | |
func main() { | |
// Use current as default dir source. | |
path, err := os.Getwd() | |
if err != nil { | |
log.Fatal(err) | |
} | |
if len(os.Args) >= 2 { | |
path = os.Args[1] | |
} | |
ip := getLocIP() | |
port := fmt.Sprintf(":%d", defaultPort) | |
log.Printf("serving %s on %s%s", path, ip, port) | |
log.Fatal(http.ListenAndServe(port, http.FileServer(http.Dir(path)))) | |
} | |
func getLocIP() net.IP { | |
ifaces, _ := net.Interfaces() | |
// handle err | |
for _, i := range ifaces { | |
addrs, _ := i.Addrs() | |
// handle err | |
for _, addr := range addrs { | |
var ip net.IP | |
switch v := addr.(type) { | |
case *net.IPNet: | |
ip = v.IP | |
case *net.IPAddr: | |
ip = v.IP | |
} | |
if i.Name == "en0" && ip.To4() != nil { | |
log.Println("local interface found", i.Name, ip.To4()) | |
return ip.To4() | |
} | |
} | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment