Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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!"

like image 695
user4611478 Avatar asked Feb 26 '15 18:02

user4611478


2 Answers

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)
}
like image 200
Cyberience Avatar answered Oct 18 '22 13:10

Cyberience


No, you cannot.

You can however start multiple listeners on different ports

go http.ListenAndServe(PORT, handlerA)
http.ListenAndServe(PORT, handlerB)
like image 24
JimB Avatar answered Oct 18 '22 13:10

JimB