Go Web 编程之 模板(二)

概述

上一篇文章中,我们介绍了 Go 模板库text/templatetext/template库用于生成文本输出。在 Web 开发中,涉及到很多安全方面的问题。有些数据是用户输入的,不能直接替换到模板中,否则可能导致注入攻击。Go 提供了html/template库处理这些问题。html/template提供了与text/template一样的接口。我们通常使用html/template生成 HTML 输出。

由于上一篇文章已经详细介绍了 Go 模板的基本概念,本文主要从使用的层面来介绍html/template库。中间会有安全方面的内容。那就开始吧!

初体验

html/template库的使用与text/template基本一样:

package main

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

func indexHandler(w http.ResponseWriter, r *http.Request) {
    t, err := template.ParseFiles("hello.html")
    if err != nil {
        w.WriteHeader(500)
        fmt.Fprint(w, err)
        return
    }

    t.Execute(w, "Hello World")
}

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", indexHandler)

    server := &http.Server {
        Addr:    ":8080",
        Handler: mux,
    }
    if err := server.ListenAndServe(); err != nil {
        log.Fatal(err)
    }
}

模板文件hello.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>Go Web 编程之 模板(二)</title>
</head>
<body>
    {
  { . }}
</body>
</html>

模板中的{ { . }}会被替换为传入的数据"Hello World",程序将模板执行后生成的文本通过ResponseWriter传回客户端。

编译,运行程序(我的环境 Win10 Git Bash):

$ go build -o main.exe main.go
$ ./main.exe

打开浏览器,输入localhost:8080,即可看到"Hello World"页面。

我们在介绍text/template库的时候,提到了空白问题

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值