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()
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记