Go学习:http: panic serving runtime error: invalid memory address or nil pointer

这个运行时错误的原因是在"net/http"的 handler func(ResponseWriter, *Request)函数里使用了没有分配内存的指针。实际上,和C语言一样所有指针在使用前都需要做nil判断。示例如下。
package main

import (
	"fmt"
	"github.com/pochard/logrotator"
	"net/http"
	"time"
)

var logger *logrotator.TimeBasedRotator

func handler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello")
    //logger是没有分配内存的指针,并且没做nil判断
	logger.Write([]byte("110032,1585038001,218.86.226.125,-,-\n"))
}

func main() {
    //这里本来是给全局变量logger赋值,但是误用了:=,导致给局部变量logger声明并赋值,而全局变量logger依然是nil
	logger, _ := logrotator.NewTimeBasedRotator("/data/web_log/cookiemapping-%Y%m%d-%H%M.log", 20*time.Minute)
	defer logger.Close()

	http.HandleFunc("/hello", handler)

	http.ListenAndServe(":8080", nil)
}
2020/03/24 16:45:17 http: panic serving 192.168.131.69:50070: runtime error: invalid memory address or nil pointer dereference
goroutine 21 [running]:
net/http.(*conn).serve.func1(0xc00010e140)
        /usr/local/go/src/net/http/server.go:1767 +0x139
panic(0x6add00, 0x9374b0)
        /usr/local/go/src/runtime/panic.go:679 +0x1b2
github.com/pochard/logrotator.(*TimeBasedRotator).Write(0x0, 0xc000182090, 0x25, 0x25, 0x0, 0x0, 0x0)
        /home/zhoupeng/go-test/pkg/mod/github.com/pochard/[email protected]/trotator.go:24 +0x40
main.handler(0x76f1c0, 0xc00017c2a0, 0xc00011e200)
        /home/zhoupeng/go-test/src/cookiemapping/checknil.go:14 +0xe2
net/http.HandlerFunc.ServeHTTP(0x71f2f8, 0x76f1c0, 0xc00017c2a0, 0xc00011e200)
        /usr/local/go/src/net/http/server.go:2007 +0x44
net/http.(*ServeMux).ServeHTTP(0x943b20, 0x76f1c0, 0xc00017c2a0, 0xc00011e200)
        /usr/local/go/src/net/http/server.go:2387 +0x1bd
net/http.serverHandler.ServeHTTP(0xc0000d2000, 0x76f1c0, 0xc00017c2a0, 0xc00011e200)
        /usr/local/go/src/net/http/server.go:2802 +0xa4
net/http.(*conn).serve(0xc00010e140, 0x76f740, 0xc0001161c0)
        /usr/local/go/src/net/http/server.go:1890 +0x875
created by net/http.(*Server).Serve
        /usr/local/go/src/net/http/server.go:2928 +0x384
发布了51 篇原创文章 · 获赞 3 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/pengpengzhou/article/details/105075535