golang基础-模板渲染(终端、浏览器)、渲染输出文件、自定义io.Writer渲染

模板渲染终端

1)替换 {{.字段名}}

demo.go

package main

import (
    "fmt"
    "os"
    "text/template"
)

type Person struct {
    Name string
    age  string
}

func main() {
    t,err := template.ParseFiles("e:/golang/go_pro/src/safly/index.html")
    if err != nil {
        fmt.Println("parse file err:",err)
        return
    }
    p := Person{Name: "Mary",age: "31"}
    if err := t.Execute(os.Stdout,p); err != nil {
        fmt.Println("There was an error:",err.Error())
    }
}

index.html

<html> <head> <title> </title> </head> <body> <p> <!--p代表当前对象--> hello,{{.Name}} {{.}} </p> </body> </html>

然后在终端就可以渲染输出如下:

PS E:\golang\go_pro\src\safly> go run demo.go
<html>

<head>
    <title>
    </title>
</head>

<body>
    <p>
        <!--p代表当前对象-->
        hello,Mary
        {Mary 31}
    </p>
</body>
</html>
PS E:\golang\go_pro\src\safly>

模板渲染浏览器输出

index.html保持不变

package main

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

var myTemplate *template.Template

type Person struct {
    Name string
    age  string
}


func userInfo(w http.ResponseWriter,r *http.Request) {

    p := Person{Name:"safly",age:"30"}
    myTemplate.Execute(w,p)

}

func initTemplate(fileName string) (err error){
    myTemplate,err  = template.ParseFiles(fileName)
    if err != nil{
        fmt.Println("parse file err:",err)
        return
    }
    return
}
/* func HandleFunc(pattern string,handler func(ResponseWriter,*Request)) { DefaultServeMux.HandleFunc(pattern,handler) } */

func main() {
    initTemplate("e:/golang/go_pro/src/safly/index.html")
    http.HandleFunc("/user/info",userInfo)
    err := http.ListenAndServe("0.0.0.0:8880",nil)
    if err != nil {
        fmt.Println("http listen Failed")
    }
}

模板渲染存储文件

package main

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

var myTemplate *template.Template

type Person struct {
    Name string
    age  string
}


func userInfo(w http.ResponseWriter,age:"30"}

    myTemplate.Execute(os.Stdout,p)
    file,err := os.OpenFile("demo.dat",os.O_CREATE|os.O_WRONLY, 0755)
    if err != nil {
        fmt.Println("open Failed err:",err)
        return
    }
    myTemplate.Execute(file,p)
}

func initTemplate(fileName string) (err error){
    myTemplate,nil)
    if err != nil {
        fmt.Println("http listen Failed")
    }
}

然后demo.dat就被渲染输出内容了:

自定义io.Writer渲染

我们看下myTemplate.Execute源码

func (t *Template) Execute(wr io.Writer,data interface{}) error {
    if err := t.escape(); err != nil {
        return err
    }
    return t.text.Execute(wr,data)
}
type Writer interface { Write(p []byte) (n int,err error) }

所以我们实现Writer接口方法Write就可以自定义

package main

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

var myTemplate *template.Template

type Person struct {
    Name string
    age  string
}

type Result struct {
    output string
}
/* 自定义实现接口 type Writer interface { Write(p []byte) (n int,err error) } */
func (p *Result) Write(b []byte) (n int,err error) {
    fmt.Println("called by template")
    p.output += string(b)
    return len(b),nil
}

/* func WriteString(w Writer,s string) (n int,err error) { if sw,ok := w.(stringWriter); ok { return sw.WriteString(s) } return w.Write([]byte(s)) } */

func userInfo(w http.ResponseWriter,r *http.Request) {
    p := Person{Name:"safly",age:"30"}

    resultWriter := &Result{}
    io.WriteString(resultWriter,"hello world")

    myTemplate.Execute(resultWriter,p)
    fmt.Println("render data:",resultWriter.output)
}

func initTemplate(fileName string) (err error){
    myTemplate,nil)
    if err != nil {
        fmt.Println("http listen Failed")
    }
}

我们在浏览器中输入http://localhost:8880/user/info
然后在终端就会渲染出如下内容

PS E:\golang\go_pro\src\safly> go run demo.go
called by template
called by template
called by template
called by template
called by template
called by template
render data: hello world<html>

<head>
    <title>
    </title>
</head>

<body>
    <p>

        hello,safly
        {safly 30}
    </p>
</body>
</html>

相关文章

程序目录结构 简单实现,用户登录后返回一个jwt的token,下次请求带上token请求用户信息接口并返回信息...
本篇博客的主要内容是用go写一个简单的Proof-of-Work共识机制,不涉及到网络通信环节,只是一个本地的简...
简介 默克尔树(MerkleTree)是一种典型的二叉树结构,其主要特点为: 最下面的叶节点包含存储数据或其...
接下来学习并发编程, 并发编程是go语言最有特色的地方, go对并发编程是原生支持. goroutine是go中最近本...
先普及一下, 什么是广度优先搜索 广度优先搜索类似于树的层次遍历。从图中的某一顶点出发,遍历每一个顶...
第一天: 接口的定义和实现 第二天: 一. go语言是面向接口编程. 在学习继承的时候说过, go语言只有封装,...