In a recent project, I came across a requirement to simultaneously listen on multiple sets of ports with different routes, and have the ability to control the open/close status of each listening group. I aim to achieve this functionality using only the built-in packages provided by Go.

Initially, I tried using Go's http.Server, which met most of my needs. However, it seemed to lack support for handling different routes. Here's my code.

func (location *location) listen(mu *sync.Mutex, servicesPoll *map[string]*location) {
    server := &http.Server{
        Addr: location.root,
        Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            switch location.locationType {
            case loadBalancing:
                location.hashRing.forward(w, r, mu)
            case fileService:
                location.getFile(w, r, mu)
            }
        }),
    }
    location.httpService = server
    (*servicesPoll)[location.root] = location

    err := server.ListenAndServe()
    if err != nil {
        if err.Error() == "http: Server closed" {
            return
        }
        log.Println("l", location.root, "error,info:", err)
    }
}
0

There are 0 best solutions below