3 回答
TA貢獻1719條經驗 獲得超6個贊
您的問題有點誤導,因為它詢問如何在 Web 瀏覽器中打開本地頁面,但您實際上想知道如何啟動 Web 服務器以便可以在瀏覽器中打開它。
對于后者(啟動 Web 服務器以提供靜態文件),您可以使用該http.FileServer()功能。有關更詳細的答案,請參閱:Include js file in Go template和With golang webserver where does the root of the website map into the filesystem>。
為您的文件夾提供服務的示例/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) {
fmt.Fprint(w, "Hello from Go")
}
func main() {
http.HandleFunc("/", myHandler)
panic(http.ListenAndServe(":8080", nil))
}
至于第一個(在默認瀏覽器中打開頁面),Go 標準庫中沒有內置支持。但這并不難,您只需執行特定于操作系統的外部命令。您可以使用這個跨平臺解決方案(我也在我的github.com/icza/gox庫中發布了它,請參閱osx.OpenDefault()):
// open opens the specified URL in the default browser of the user.
func open(url string) error {
var cmd string
var args []string
switch runtime.GOOS {
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;披露:我是作者)。
請注意,exec.Command()如果需要,執行特定于操作系統的參數引用。因此,例如,如果 URL 包含&,它將在 Linux 上正確轉義,但是,它可能無法在 Windows 上運行。在 Windows 上,您可能必須自己手動引用它,例如將&符號替換"^&"為strings.ReplaceAll(url, "&", "^&").
使用它在您的默認瀏覽器中打開之前啟動的網絡服務器:
open("http://localhost:8080/")
最后要注意的一件事:http.ListenAndServe()阻塞并且永不返回(如果沒有錯誤)。所以你必須在另一個 goroutine 中啟動服務器或瀏覽器,例如:
go open("http://localhost:8080/")
panic(http.ListenAndServe(":8080", nil))
TA貢獻1853條經驗 獲得超18個贊
根據 Paul 的回答,這里有一個適用于 Windows 的解決方案:
package main
import (
"log"
"net/http"
"os/exec"
"time"
)
func main() {
http.HandleFunc("/", myHandler)
go func() {
<-time.After(100 * time.Millisecond)
err := exec.Command("explorer", "http://127.0.0.1:8080").Run()
if err != nil {
log.Println(err)
}
}()
log.Println("running at port localhost:8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
TA貢獻1995條經驗 獲得超2個贊
這是一個相當普遍的問題。你可以使用xdg-open程序為你做這件事。只需從 Go 運行該過程。will fork 自己,xdg-open所以我們可以簡單地使用Run并等待進程結束。
package main
import "os/exec"
func main() {
exec.Command("xdg-open", "http://example.com/").Run()
}
- 3 回答
- 0 關注
- 452 瀏覽
添加回答
舉報
