啟動網頁伺服器,http – 如何在golang中啟動Web伺服器在瀏覽器中開啟頁面?
您的問題有點誤導,因為它詢問如何在Web瀏覽器中開啟本地頁面,但您實際上想知道如何啟動Web伺服器以便可以在瀏覽器中開啟它.
服務/ tmp / data資料夾的示例:
http.Handle("/", http.FileServer(http.Dir("/tmp/data")))
panic(http.ListenAndServe(":8080", nil))
如果你想提供動態內容(由Go程式碼生成),你可以使用net/http包並編寫自己的處理程式來生成響應,例如:
func myHandler(w http.ResponseWriter, r *http.Request) {undefined
fmt.Fprint(w, "Hello from Go")
}
func main() {undefined
http.HandleFunc("/", myHandler)
panic(http.ListenAndServe(":8080", nil))
}
至於第一個(在預設瀏覽器中開啟一個頁面),Go標準庫中沒有內建支援.但這並不難,你只需要執行特定於作業系統的外部命令.您可以使用此跨平臺解決方案:
// open opens the specified URL in the default browser of the user.
func open(url string) error {undefined
var cmd string
var args []string
switch runtime.GOOS {undefined
case "windows":
cmd = "cmd"
args = []string{"/c", "start"}
case "darwin":
cmd = "open"
default: // "linux", "freebsd", "openbsd", "netbsd"
cmd = "xdg-open"
}
args = append(args, url)
return exec.Command(cmd, args...).Start()
}
此示例程式碼取自Gowut(Go Web UI Toolkit;披露:我是作者).
使用此命令在預設瀏覽器中開啟以前啟動的Web伺服器:
open("http://localhost:8080/")
最後要注意的是:http.ListenAndServe()塊並且永不返回(如果沒有錯誤).所以你必須在另一個goroutine中啟動伺服器或瀏覽器,例如:
go open("http://localhost:8080/")
panic(http.ListenAndServe(":8080", nil))