Skip to content

Instantly share code, notes, and snippets.

@kudarap
Created July 1, 2020 11:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kudarap/590b725fabecb4324f10f5ebca3d29d2 to your computer and use it in GitHub Desktop.
Save kudarap/590b725fabecb4324f10f5ebca3d29d2 to your computer and use it in GitHub Desktop.
file serving though local netowk
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