douhan8610 2019-03-08 10:46
浏览 5
已采纳

具有自己实现的处理程序的服务器未连续侦听

I am trying to understand how to implement http.Handler, correctly. I wrote the barebone package code. Here is my package code

package app

import (
    "fmt"
    "net/http"
)

//Handler is the handler function
type Handler struct {
}

func (h *Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
    fmt.Println("Running ServeHTTP")
    rw.Write(([]byte)("Hello"))
    return
}

//NewHandler is
func NewHandler() *Handler {
    return &Handler{}
}

//Start will start the server
func (h *Handler) Start() {
    fmt.Println("Running Start")
    http.ListenAndServe("8080", h)

}

I made a directory in the abovementioned package named it "examples". I made a file main.go and wrote this in main function(After importing the Package).

func main() {

    handler := app.NewHandler()

    handler.Start()
}

But, when I run it with go run *.go, The Program abrupts almost instantly after writing Running Start on console. Shouldn't it listen continuouly. What am I doing wrong?

  • 写回答

1条回答 默认 最新

  • douye1940 2019-03-08 10:54
    关注

    The http.ListenAndServe() func returns error. You could just check that by logging:

    fmt.Println(http.ListenAndServe("8000", h))
    

    and you will see that in your case its returning an error causing the function to return.

    All you need to do is to pass address as :8000

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗