Created
December 5, 2018 07:08
-
-
Save fand/abd37d781957e7d53464d0c067dd0176 to your computer and use it in GitHub Desktop.
easy http server
This file contains hidden or 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 ( | |
"fmt" | |
"log" | |
"net/http" | |
"os" | |
"os/exec" | |
"path/filepath" | |
"runtime" | |
) | |
// https://gist.github.com/hyg/9c4afcd91fe24316cbf0 | |
func openbrowser(url string) { | |
var err error | |
switch runtime.GOOS { | |
case "linux": | |
err = exec.Command("xdg-open", url).Start() | |
case "windows": | |
err = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start() | |
case "darwin": | |
err = exec.Command("open", url).Start() | |
default: | |
err = fmt.Errorf("unsupported platform") | |
} | |
if err != nil { | |
log.Fatal(err) | |
} | |
} | |
func main() { | |
// Get directory path | |
ex, err := os.Executable() | |
if err != nil { | |
panic(err) | |
} | |
dir, err := filepath.Abs(filepath.Dir(ex)) | |
if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Println(dir) | |
done := make(chan bool) | |
// Launch HTTP server | |
fs := http.FileServer(http.Dir(dir)) | |
http.Handle("/", fs) | |
go http.ListenAndServe(":80", nil) | |
fmt.Println("gonna open") | |
// Open index.html in browser | |
openbrowser("http://localhost/index.html") | |
// Await web server close | |
<-done | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment