Last active
December 24, 2015 21:29
-
-
Save yanolab/6866130 to your computer and use it in GitHub Desktop.
Simple GO static web contents server.
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 ( | |
"errors" | |
"flag" | |
"fmt" | |
"log" | |
"net" | |
"net/http" | |
"os" | |
) | |
type logging struct { | |
baseHandler http.Handler | |
} | |
func (l *logging) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
log.Printf("%s -> %s %s %s ", r.RemoteAddr, r.Method, r.Proto, r.URL) | |
l.baseHandler.ServeHTTP(w, r) | |
} | |
func externalIP() (string, error) { | |
ifaces, err := net.Interfaces() | |
if err != nil { | |
return "", err | |
} | |
for _, iface := range ifaces { | |
if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 { | |
continue // interface down or loopback interface | |
} | |
addrs, err := iface.Addrs() | |
if err != nil { | |
return "", 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 ip == nil || ip.IsLoopback() { | |
continue | |
} | |
ip = ip.To4() | |
if ip == nil { | |
continue // not an ipv4 address | |
} | |
return ip.String(), nil | |
} | |
} | |
return "", errors.New("are you connected to the network?") | |
} | |
var port int | |
var host string | |
var homeDir string | |
func init() { | |
addr, _ := externalIP() | |
flag.IntVar(&port, "port", 8000, "listening port") | |
flag.StringVar(&host, "addr", addr, "bind address") | |
flag.Parse() | |
homeDir = flag.Arg(0) | |
if homeDir == "" { | |
homeDir = "./" | |
} | |
} | |
func main() { | |
if fi, err := os.Stat(homeDir); err != nil { | |
panic(err) | |
} else if !fi.IsDir() { | |
fmt.Printf("%s is not directory.\n", homeDir) | |
os.Exit(1) | |
} | |
log.Printf("serve on %s:%d at %s\n", host, port, homeDir) | |
handler := &logging{baseHandler: http.FileServer(http.Dir(homeDir))} | |
panic(http.ListenAndServe(fmt.Sprintf("%s:%d", host, port), handler)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment