go 模板

Posted lajiao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了go 模板相关的知识,希望对你有一定的参考价值。

package main

import (
    "fmt"
    "log"
    "net/http"
    "os"
    "text/template"
)

type Person struct {
    Name string
    age  string
}
func GetTest(w http.ResponseWriter, r *http.Request){
    t, err := template.ParseFiles("F:\\go_test\\src\\10_http\\index.html")
    if err != nil {
        fmt.Println("parse file err:", err)
        return
    }
    p := Person{Name: "Mary", age: "31"}
    file, err := os.OpenFile("testxxx.txt", os.O_CREATE|os.O_RDONLY, 0755)
    defer file.Close()
    if err != nil{

    }

    //if err := t.Execute(os.Stdout, p); err != nil {  // 输出终端
    //if err := t.Execute(w, p); err != nil { // 输出网页
    if err := t.Execute(file, p); err != nil { // 输出文件
        fmt.Println("There was an error:", err.Error())
    }

}


func main() {
    fmt.Println("listening...")
    http.HandleFunc("/test", GetTest)
    http.HandleFunc("/test1", logPanics(SimpleServer))
    http.HandleFunc("/test2", logPanics(FormServer))
    if err := http.ListenAndServe(":8088", nil); err != nil {
        fmt.Println("listen error")
    }
}

func logPanics(handle http.HandlerFunc) http.HandlerFunc {
    return func(writer http.ResponseWriter, request *http.Request) {
        defer func() {
            if x := recover(); x != nil {
                log.Printf("[%v] caught panic: %v", request.RemoteAddr, x)
            }
        }()
        handle(writer, request)
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{{.Name}}hello!{{.}}
</body>
</html>

以上是关于go 模板的主要内容,如果未能解决你的问题,请参考以下文章

VSCode自定义代码片段2——.vue文件的模板

VSCode自定义代码片段(vue主模板)

[Go] 通过 17 个简短代码片段,切底弄懂 channel 基础

解决go: go.mod file not found in current directory or any parent directory; see ‘go help modules‘(代码片段

Eclipse 中的通用代码片段或模板

你知道的Go切片扩容机制可能是错的