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

在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
    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()
    
    }
    
    点赞 评论

相关推荐