Answer the question
In order to leave comments, you need to log in
Why doesn't Template html work in GO?
Can you please tell me why the error occurs?
Compiling is fine, launching too, the site gives a 404 Error, and an error is thrown in the code.
All my code is located in /root/go
The profile says
export GOPATH=$HOME/go
export PATH=$PATH:/usr/local/go/bin:$GOPATH/bin
package main
import (
"fmt"
"html/template"
"net/http"
)
func indexHandler(w http.ResponseWriter, r *http.Request){
t, err := template.ParseFiles("templates/ip/index.html")
if err != nil {
fmt.Fprintf(w, err.Error())
}
t.ExecuteTemplate(w, "index", nil)
}
func main() {
http.HandleFunc("/", indexHandler)
http.ListenAndServe(":9001", nil)
}
<!DOCTYPE html>
<html>
<head>
<title>text</title>
</head>
<body>
[email protected]:~# ./ipa
2017/02/08 03:46:01 http: panic serving 127.0.0.1:61620: runtime error: invalid memory address or nil pointer dereference
goroutine 5 [running]:
net/http.(*conn).serve.func1(0xc4200c6280)
/usr/local/go/src/net/http/server.go:1491 +0x12a
panic(0x6d4ca0, 0xc42000c0d0)
/usr/local/go/src/runtime/panic.go:458 +0x243
html/template.(*Template).lookupAndEscapeTemplate(0x0, 0x7269f6, 0x5, 0x0, 0x0, 0x0)
/usr/local/go/src/html/template/template.go:125 +0x67
html/template.(*Template).ExecuteTemplate(0x0, 0x8825c0, 0xc420015e10, 0x7269f6, 0x5, 0x0, 0x0, 0x37, 0x0)
/usr/local/go/src/html/template/template.go:114 +0x43
main.indexHandler(0x885fc0, 0xc420015e10, 0xc4200f80f0)
/root/go/src/ipa/ipa.go:16 +0xe4
net/http.HandlerFunc.ServeHTTP(0x7535b8, 0x885fc0, 0xc420015e10, 0xc4200f80f0)
/usr/local/go/src/net/http/server.go:1726 +0x44
net/http.(*ServeMux).ServeHTTP(0x8a5dc0, 0x885fc0, 0xc420015e10, 0xc4200f80f0)
/usr/local/go/src/net/http/server.go:2022 +0x7f
net/http.serverHandler.ServeHTTP(0xc4200c6200, 0x885fc0, 0xc420015e10, 0xc4200f80f0)
/usr/local/go/src/net/http/server.go:2202 +0x7d
net/http.(*conn).serve(0xc4200c6280, 0x886600, 0xc420016440)
/usr/local/go/src/net/http/server.go:1579 +0x4b7
created by net/http.(*Server).Serve
/usr/local/go/src/net/http/server.go:2293 +0x44d
Answer the question
In order to leave comments, you need to log in
Everything worked! Added
{{ index }} and {{ end }} to index.html
and changed path from
t, err := template.ParseFiles("templates/ip/index.html")
to
t, err := template.ParseFiles(" /root/go/templates/ip/index.html")
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question