亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何啟動Web服務器以在golang的瀏覽器中打開頁面?

如何啟動Web服務器以在golang的瀏覽器中打開頁面?

Go
一只斗牛犬 2022-03-07 22:38:01
如何使用 golang 在瀏覽器中臨時打開網頁?就像這里是如何在python中使用HTTPServer完成的。
查看完整描述

3 回答

?
慕俠2389804

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))


查看完整回答
反對 回復 2022-03-07
?
慕容森

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))

}


查看完整回答
反對 回復 2022-03-07
?
拉風的咖菲貓

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()

}


查看完整回答
反對 回復 2022-03-07
  • 3 回答
  • 0 關注
  • 452 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號