'Can I setup multi port from one web app with Go?

As I know, I can run simple web server with Golang just use http package, like

http.ListenAndServe(PORT, nil)

where PORT is TCP address to listen.

Can I use PORT as PORTS, for example http.ListenAndServe(":80, :8080", nil) from one application?

Possible my question is stupid, but "Who don't ask, He will not get answer!"

go


Solution 1:[1]

Here is a simple working Example:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Cyberience