Skip to content

Instantly share code, notes, and snippets.

@fand
Created December 5, 2018 07:08
Show Gist options
  • Save fand/abd37d781957e7d53464d0c067dd0176 to your computer and use it in GitHub Desktop.
Save fand/abd37d781957e7d53464d0c067dd0176 to your computer and use it in GitHub Desktop.
easy http server
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