Skip to content

Instantly share code, notes, and snippets.

@fand fand/server.go
Created Dec 5, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.