Created
September 29, 2016 15:44
-
-
Save suconghou/eb1c197dce219322c6c73d3bfd8bf2a6 to your computer and use it in GitHub Desktop.
go http file 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 ( | |
"flag" | |
"fmt" | |
"net/http" | |
"os" | |
"path" | |
"strconv" | |
) | |
var ( | |
port = flag.Int("p", 6060, "http server port") | |
root = flag.String("d", "./", "root document dir") | |
) | |
func main() { | |
flag.Parse() | |
pwd, err := os.Getwd() | |
if err != nil { | |
fmt.Println(err) | |
os.Exit(1) | |
} | |
var ( | |
doc string | |
) | |
if path.IsAbs(*root) { | |
doc = *root | |
} else { | |
doc = path.Join(pwd, *root) | |
} | |
if _, err := os.Stat(doc); err == nil { | |
fmt.Println("Server listening on port " + strconv.Itoa(*port)) | |
fmt.Println("Document root " + doc) | |
error := http.ListenAndServe(":"+strconv.Itoa(*port), http.FileServer(http.Dir(doc))) | |
if error != nil { | |
fmt.Println("Error listening:", error.Error()) | |
os.Exit(1) | |
} | |
} else { | |
fmt.Println(doc + " not exists") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment