Goroutines with ListenAndServe increases productivity?

I am not very good at Go procedures, but since I work with a router net/http, I have seen several times what ListenAndServe()the go routine wraps around.

The server must be able to handle multiple requests simultaneously from the box in order to be effective. So why do you use procedures as "light threads"? Does concurrency have any benefits?

Here is an example of OpenShift

package main

import (
    "fmt"
    "net/http"
)

func helloHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Hello OpenShift!")
}

func main() {
    http.HandleFunc("/", helloHandler)

    go func() {
        fmt.Println("serving on 8080")
        err := http.ListenAndServe(":8080", nil)
        if err != nil {
            panic("ListenAndServe: " + err.Error())
        }
    }()

    go func() {
        fmt.Println("serving on 8888")
        err := http.ListenAndServe(":8888", nil)
        if err != nil {
            panic("ListenAndServe: " + err.Error())
        }
    }()
    select {}
}
+4
source share
2 answers

http.ListenAndServeis a blocking call. If you want to do another job (for example, make a second call http.ListenAndServe), you need to move it to a separate goroutine. That is all they do here.

select{} , goroutine, http.ListenAndServe goroutines. select{}, , main() .

, select{} go func() . , , .

.

. :

func main() {
    http.HandleFunc("/", responsehandler.Handler)
    go func() {
      http.ListenAndServe(":8888", nil)
    }()
    fileservice.NewWatcher()
}

http.ListenAndServe, fileservice.NewWatcher() ( ). goroutine, fileservice.NewWatcher() .

- :

func init() {
    go func() {
        log.Println(http.ListenAndServe("localhost:6060", nil))
    }()
}

- . , goroutine, init , . import _ "profiling" " " - .

+4

, " ".

+1

All Articles