我可以使用Go从一个Web应用程序设置多端口吗?

use*_*478 6 go

据我所知,我可以使用Golang运行简单的Web服务器,就像使用http包一样

http.ListenAndServe(PORT, nil)
Run Code Online (Sandbox Code Playgroud)

其中PORT是要侦听的TCP地址.

我可以将PORT用作PORT S,例如http.ListenAndServe(":80, :8080", nil)来自一个应用程序吗?

可能我的问题是愚蠢的,但"谁不问,他不会得到答案!"

谢谢你提前!

Jim*_*imB 13

你不能.

但是,您可以在不同的端口上启动多个侦听器

go http.ListenAndServe(PORT, handlerA)
http.ListenAndServe(PORT, handlerB)
Run Code Online (Sandbox Code Playgroud)

  • 然后使用相同的处理程序; 你自己尝试这些更容易.如果你不确定goroutine是什么,你真的需要从这里开始:http://golang.org/doc/ (2认同)

Cyb*_*nce 9

这是一个简单的工作示例:

package main

import (
    "fmt"
    "net/http"
)

func hello(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "hello")
}

func world(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "world")
}

func main() {
    serverMuxA := http.NewServeMux()
    serverMuxA.HandleFunc("/hello", hello)

    serverMuxB := http.NewServeMux()
    serverMuxB.HandleFunc("/world", world)

    go func() {
        http.ListenAndServe("localhost:8081", serverMuxA)
    }()

    http.ListenAndServe("localhost:8082", serverMuxB)
}
Run Code Online (Sandbox Code Playgroud)