golang的 Web 开发,提示找不到模板文件

前端之家收集整理的这篇文章主要介绍了golang的 Web 开发,提示找不到模板文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

编译后的可执行文件,与模板文件在同一目录,报错:no files

代码

package main

import (
	"fmt"
	"html/template"
	"log"
	"net/http"
	"os"
	"strings"
)

func sayhelloName(w http.ResponseWriter,r *http.Request) {
	r.ParseForm() // 解析URL传递的参数, 对于post则解析响应包的主体(request body)
	// 注意:如果没有调用ParseForm方法,下面无法获取表单数据
	fmt.Println(r.Form) // 这些信息是输出到服务器端的打印信息
	fmt.Println("path",r.URL.Path)
	fmt.Println("scheme",r.URL.Scheme)
	fmt.Println(r.Form["url_long"])
	for k,v := range r.Form {
		fmt.Println("key:",k)
		fmt.Println("val:",strings.Join(v,""))
	}

	fmt.Fprintf(w,"Hello April") // 这个写入到w的是输出到客户端的
}

func login(w http.ResponseWriter,r *http.Request) {
	fmt.Println("method:",r.Method) // 获取请求的方法
	wd,oserr := os.Getwd()
	fmt.Println(wd)
	fmt.Println(oserr)
	if r.Method == "GET" {
		t,err := template.ParseGlob("login.gtpl")
		fmt.Println(err)
		t.Execute(w,"")
	} else {
		r.ParseForm()
		// 请求的是登录数据,那么执行登录的逻辑判断
		fmt.Println("username:",r.Form["username"])
		fmt.Println("password:",r.Form["password"])
	}
}

func main() {
	http.HandleFunc("/",sayhelloName)
	http.HandleFunc("/login",login)
	err := http.ListenAndServe(":9090",nil)
	if err != nil {
		log.Fatal("ListenAndServe:",err)
	}
}

错误信息:

html/template: pattern matches no files: `login.gtpl`
2016/07/18 15:12:03 http: panic serving [::1]:65036: runtime error: invalid memory address or nil pointer dereference
goroutine 20 [running]:
net/http.(*conn).serve.func1(0xc8200ec100)
	/usr/local/go/src/net/http/server.go:1389 +0xc1
panic(0x39f4e0,0xc82000a0e0)
	/usr/local/go/src/runtime/panic.go:443 +0x4e9
html/template.(*Template).escape(0x0,0x0,0x0)
	/usr/local/go/src/html/template/template.go:79 +0x3c
html/template.(*Template).Execute(0x0,0x13858d0,0xc820071ee0,0x301b60,0xc82006cf90,0x0)
	/usr/local/go/src/html/template/template.go:101 +0x34
main.login(0x13857d0,0xc820122000)
	/Users/KJRS/gowork/src/learn/4/web.go:35 +0x546
net/http.HandlerFunc.ServeHTTP(0x4ca680,0x13857d0,0xc820122000)
	/usr/local/go/src/net/http/server.go:1618 +0x3a
net/http.(*ServeMux).ServeHTTP(0xc82006ed80,0xc820122000)
	/usr/local/go/src/net/http/server.go:1910 +0x17d
net/http.serverHandler.ServeHTTP(0xc8200ec080,0xc820122000)
	/usr/local/go/src/net/http/server.go:2081 +0x19e
net/http.(*conn).serve(0xc8200ec100)
	/usr/local/go/src/net/http/server.go:1472 +0xf2e
created by net/http.(*Server).Serve
	/usr/local/go/src/net/http/server.go:2137 +0x44e
原文链接:https://www.f2er.com/go/189527.html

猜你在找的Go相关文章