douqi2571 2019-08-23 19:23 采纳率: 0%
浏览 352
已采纳

在Go中创建多个http Server实例不起作用

I am trying to create 2 HTTP server in my go lang app and this is how I try to achieve it :

package main

import (
    "net/http"
)

func main() {

    server := http.Server{
        Addr:    ":9000",
        //Handler:  http.HandleFunc("/", hello)
    }
    server.ListenAndServe()


    server2 := http.Server{
        Addr:    ":8000",
        //Handler:  http.HandleFunc("/", hello)
    }
    server2.ListenAndServe()

}

The issue I am having is when I go to the browser to make a request to http://localhost:9000/ it goes, but when I make a request to http://localhost:8000/ I get "Site cannot be reached". Why can't I create to instances of an HTTP server in Go?

  • 写回答

1条回答 默认 最新

  • dtcyv3985 2019-08-23 19:32
    关注

    Just like Tim Cooper was saying ListenAndServe is blocking so the first server starts up, but then does not proceed to the second call. An easy way to fix this would be to start server in a goroutine of its own like

    func main() {
    
        server := http.Server{
            Addr:    ":9000",
            //Handler:  http.HandleFunc("/", hello)
        }
        go server.ListenAndServe()
    
    
        server2 := http.Server{
            Addr:    ":8000",
            //Handler:  http.HandleFunc("/", hello)
        }
        server2.ListenAndServe()
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?