How to start a web server to open a page in a browser in golang?

How to temporarily open a webpage in a browser using golang?

How to do this using HTTPServer in python.

+4
source share
4 answers

Your question is a little misleading as it asks how to open a local page in a web browser, but you really want to know how to start the web server so that it can be opened in the browser.

( - ) http.FileServer(). . js Go - golang, > .

/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 . , , . - :

// 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, : ).

- :

open("http://localhost:8080/")

: http.ListenAndServe() ( ). , goroutine, :

go open("http://localhost:8080/")
panic(http.ListenAndServe(":8080", nil))

, -: : , ?

+13

. xdg-open, . Go. xdg-open , Run .

package main

import "os/exec"

func main() {
    exec.Command("xdg-open", "http://example.com/").Run()
}
0

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

, - , , , , . Linux- xdg , xdg, "firefox", "xdg-open". , -, . -, , , URL- - .

package main

import (
    "fmt"
    "net/http"
    "time"
)

func myHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "Hello from Go")
}

func main() {
    http.HandleFunc("/", myHandler)
    go func() {
        <-time.After(100 * time.Millisecond)
        open("http://localhost:8080/")
    }()
    panic(http.ListenAndServe(":8080", nil))
}
-1

Source: https://habr.com/ru/post/1653607/


All Articles