douxi3233 2016-11-20 20:00
浏览 28
已采纳

Go:无法在go例程中创建服务器

When trying to ListenAndServer inside a go routine I get an error:

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    http.HandleFunc("/static/", myHandler)
    go func() {
        http.ListenAndServe("localhost:80", nil)
    }()

    fmt.Printf("we are here")
    resp, _ := http.Get("localhost:80/static")

    ans, _ := ioutil.ReadAll(resp.Body)
    fmt.Printf("response: %s", ans)
}

func myHandler(rw http.ResponseWriter, req *http.Request) {
    fmt.Printf(req.URL.Path)
}

The error:

panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x48 pc=0x401102]

goroutine 1 [running]:
panic(0x6160c0, 0xc0420080a0)
        c:/go/src/runtime/panic.go:500 +0x1af
main.main()
        C:/gowork/src/exc/14.go:20 +0xc2
exit status 2

All I want is to create an http server. And then test it and connect to it from the code. What's wrong with Go? (or with me?)

  • 写回答

1条回答 默认 最新

  • duanba2001 2016-11-21 05:21
    关注

    You must use (with "http://" in this case)

    resp, _ := http.Get("http://localhost:80/static")
    

    and check the errors before use the response, just in case the request fails

    resp, err := http.Get("http://localhost:80/static")
    if err != nil {
        // do something
    } else {
        ans, _ := ioutil.ReadAll(resp.Body)
        fmt.Printf("response: %s", ans)
    }
    

    Also, if you want to get any response from your handler, you have to write a response in it.

    func myHandler(rw http.ResponseWriter, req *http.Request) {
        fmt.Printf(req.URL.Path)
        rw.Write([]byte("Hello World!"))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型