go的http-server-with-template

1,拆分版

main/main.go

package main

import (
	"fmt"
	"net/http"
)

func main() {
	http.HandleFunc("/", SimpleServer)
	fmt.Println("Starting server...")
	err := http.ListenAndServe(":8888", nil)
	if err != nil {
		fmt.Println("Http Listen Failed, err:", err)
	}

}


main/Process.go

package main

type Person struct {
	Name string
	Age string
}


main/SimpleServer.go

package main

import (
	"fmt"
	"html/template"
	"net/http"
)

func SimpleServer(w http.ResponseWriter, request *http.Request) {
	t, err := template.ParseFiles("./index.html")
	if err != nil {
		fmt.Println("Parse file err:", err)
		return
	}
	p := Person{
		Name: "ismdeep",
		Age:  "18",
	}
	if err := t.Execute(w, p); err != nil {
		fmt.Println("There was an error:", err.Error())
	}
}

外层index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width={device-width}, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1>Hello {{.Name}}</h1>
    {{if gt .Age 18}}
    <p>age 大于 18</p>
    {{else}}
    <p>age 小于 18</p>
    {{end}}
    <hr>
    <p>{{.}}</p>
</body>
</html>

2,升级版

package main

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

var myTemplate *template.Template

// 模仿http.ResponseWriter,file 等对象,做一个Write接口,实现Write方法
type Result struct {
	output  string
}
func (p *Result) Write(b []byte) (n int, exx error){
	fmt.Println("called by template")
	p.output += string(b)
	return len(b),nil
}

type Person struct {
	Name  string
	Age   int
	Title string
}

func userInfo(w http.ResponseWriter, r *http.Request) {
	fmt.Println("handle hello")
	// fmt.Fpintf(n,"hel1lo")
	p := Person{Name: "Mary", Age: 31, Title: "我的个人网站"}
	myTemplate.Execute(w, p)  // 把对象p渲染写入到w http.ResponseWriter
	//mytemplate.Execute(os.Stdout, p) // 把对象p渲染写入到os.Stdout标准输入输出中去了

	file,err := os.OpenFile("c:/test.log", os.O_CREATE |os.O_WRONLY, 0755)
	if err != nil {
		fmt.Println("open failed ern:", err)
		return
	}
	myTemplate.Execute(file, p)
	resultWriter := &Result{}
	myTemplate.Execute(resultWriter,p)
	fmt.Println("template render data:",resultWriter.output)
	/*
	// Execute实际上是调用传入第一个参数的write方法  ,file,stdout 等对象的write方法,   如果没有该write接口, 写入文件, 网络,stdout得分别执行他们各自的方法,很繁琐
	在https://golang.org/pkg/io/#Writer 的write接口
	type Writer interface {
			  Write(b []byte) (n int, exx error)
		}
	//myTemplate.ExecuteStdout(file, p)
	//myTemplate.ExecuteNetwork(file, p)
	//myTemplate.ExecuteFile(file,p)
	 */
}


func initTemplate(filename string) (err error) {
	myTemplate, err = template.ParseFiles(filename)
	if err != nil {
		fmt.Println("parse file err:", err)
		return
	}
	return
}
func main() {
	//initTemplate("d/rx-rune-go-master/go/src/go_dev/day10/template/main/index.html")
	initTemplate(	"D:\\rx-rune-go-master/go/src/go_dev/day10/template/main/index.html")
	http.HandleFunc("/user/info", userInfo)
	err := http.ListenAndServe("0.0.0.0:8888", nil)
	if err != nil {
		fmt.Println("http listen failed")
	}
}
posted @ 2022-03-05 16:07  ty1539  阅读(29)  评论(0编辑  收藏  举报