0

如题:

package main

import (
    "github.com/gin-gonic/gin"
    "net/http"
)

func main() {
    r := gin.Default()
    r.GET("/login", func(context *gin.Context) {
        context.HTML(http.StatusOK, "login.html", gin.H{})
    })
    r.Run(":8080")
}
{{define "login.html"}}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="http://127.0.0.1:8080/login" method="post">
    用户名:<input type="text" name="username" />
    密码:<input type="password" name="password" />
    <input type="submit" value="登陆" />
</form>
</body>
</html>
{{end}}

报错

runtime error: invalid memory address or nil pointer dereference
C:/Go/src/runtime/panic.go:513 (0x42cc46)
gopanic: reflectcall(nil, unsafe.Pointer(d.fn), deferArgs(d), uint32(d.siz), uint32(d.siz))

C:/Go/src/runtime/panic.go:82 (0x42bd44)

panicmem: panic(memoryError)

C:/Go/src/runtime/signal_windows.go:204 (0x43fda0)

sigpanic: panicmem()

C:/Go/gocode/src/github.com/gin-gonic/gin/context.go:764 (0x94e4ec)

(*Context).HTML: instance := c.engine.HTMLRender.Instance(name, obj)

C:/Go/gocode/src/demo/main.go:11 (0x95fa99)

main.func1: context.HTML(http.StatusOK, "login.html", gin.H{})

C:/Go/gocode/src/github.com/gin-gonic/gin/context.go:109 (0x94a8c9)

(*Context).Next: c.handlers[c.index](c)

C:/Go/gocode/src/github.com/gin-gonic/gin/recovery.go:76 (0x95d860)

RecoveryWithWriter.func1: c.Next()

C:/Go/gocode/src/github.com/gin-gonic/gin/context.go:109 (0x94a8c9)

(*Context).Next: c.handlers[c.index](c)

C:/Go/gocode/src/github.com/gin-gonic/gin/logger.go:170 (0x95cc37)

LoggerWithConfig.func1: c.Next()

C:/Go/gocode/src/github.com/gin-gonic/gin/context.go:109 (0x94a8c9)

(*Context).Next: c.handlers[c.index](c)

C:/Go/gocode/src/github.com/gin-gonic/gin/gin.go:383 (0x9542b1)

(*Engine).handleHTTPRequest: c.Next()

C:/Go/gocode/src/github.com/gin-gonic/gin/gin.go:349 (0x953ae8)

(*Engine).ServeHTTP: engine.handleHTTPRequest(c)

C:/Go/src/net/http/server.go:2741 (0x6723d1)

serverHandler.ServeHTTP: handler.ServeHTTP(rw, req)

C:/Go/src/net/http/server.go:1847 (0x66e54c)

(*conn).serve: serverHandler{c.server}.ServeHTTP(w, w.req)

C:/Go/src/runtime/asm_amd64.s:1333 (0x457690)

goexit: BYTE    $0x90    // NOP
2019-01-12 提问
1 个回答
1

已采纳
//先加载模板
r.LoadHTMLGlob("views/*")

撰写答案

推广链接