Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create many http servers into one app?

Tags:

go

I want create two http servers into one golang app. Example:

    package main

    import (
    "io"
    "net/http"
)

func helloOne(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "Hello world one!")
}

func helloTwo(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "Hello world two!")
}

func main() {
    // how to create two http server instatce? 
    http.HandleFunc("/", helloOne)
    http.HandleFunc("/", helloTwo)
    go http.ListenAndServe(":8001", nil)
    http.ListenAndServe(":8002", nil)
}

How to create two http server instance and add handlers for them?

like image 760
rusnasonov Avatar asked Dec 14 '22 13:12

rusnasonov


1 Answers

You'll need to create separate http.ServeMux instances. Calling http.ListenAndServe(port, nil) uses the DefaultServeMux (i.e. shared). The docs for this are here: http://golang.org/pkg/net/http/#NewServeMux

Example:

func main() {
    r1 := http.NewServeMux()
    r1.HandleFunc("/", helloOne)

    r2 := http.NewServeMux()
    r2.HandleFunc("/", helloTwo)

    go func() { log.Fatal(http.ListenAndServe(":8001", r1))}()
    go func() { log.Fatal(http.ListenAndServe(":8002", r2))}()
    select {}
}

Wrapping the servers with log.Fatal will cause the program to quit if one of the listeners doesn't function. If you wanted the program to stay up if one of the servers fails to start or crashes, you could err := http.ListenAndServe(port, mux) and handle the error another way.

like image 83
elithrar Avatar answered Jan 18 '23 07:01

elithrar