1 回答

TA貢獻1831條經驗 獲得超9個贊
您可以使用Go 標準庫中的html/template包來執行此操作。
這里的基本流程是:
編寫模板(go/HTML模板語言)
閱讀模板(使用
template.ParseFiles
或類似)監聽請求
將相關請求中的信息傳遞到您的模板(使用
ExecuteTemplate
或類似)
您可以將結構傳遞給ExecuteTemplate
,然后可以在您定義的模板中訪問該結構(請參見下面的示例)。例如,如果您的結構有一個名為 的字段Name
,那么您可以使用 訪問模板中的此信息{{ .Name }}
。
這是一個示例:
主要去:
包主
import (
? ? "log"
? ? "encoding/json"
? ? "html/template"
? ? "net/http"
)
var tpl *template.Template
func init() {
? ? // Read your template(s) into the program
? ? tpl = template.Must(template.ParseFiles("index.gohtml"))
}
func main() {
? ? // Set up routes
? ? http.HandleFunc("/endpoint", EndpointHandler)
? ? http.ListenAndServe(":8080", nil)
}
// define the expected structure of payloads
type Payload struct {
? ? Name string? ? ?`json:"name"`
? ? Hobby string? ? `json:"hobby"`
}
func EndpointHandler(w http.ResponseWriter, r *http.Request) {
? ? // Read the body from the request into a Payload struct
? ? var payload Payload
? ? err := json.NewDecoder(r.Body).Decode(&payload)
? ? if err != nil {
? ? ? ? log.Fatal(err)
? ? }
? ? // Pass payload as the data to give to index.gohtml and write to your ResponseWriter
? ? w.Header().Set("Content-Type", "text/html")
? ? tpl.ExecuteTemplate(w, "index.gohtml", payload)
}
索引.gohtml:
<!DOCTYPE html>
<html>
<head>
? ? <title></title>
</head>
<body>
? ? <div>
? ? ? ? <span>Your name is</span><span>{{ .Name }}</span>
? ? </div>
? ? <div>
? ? ? ? <span>Your hobby is</span><span>{{ .Hobby }}</span>
? ? </div>
</body>
</html>
樣本:
有效載荷:
{
? ? "name": "Ahmed",
? ? "hobby": "devving"
}
回復:
<!DOCTYPE html>
<html>
? ? <head>
? ? ? ? <title></title>
? ? </head>
? ? <body>
? ? ? ? <div>
? ? ? ? ? ? <span>Your name is</span>
? ? ? ? ? ? <span>Ahmed</span>
? ? ? ? </div>
? ? ? ? <div>
? ? ? ? ? ? <span>Your hobby is</span>
? ? ? ? ? ? <span>devving</span>
? ? ? ? </div>
? ? </body>
</html>
請注意,這是非常脆弱的,因此您絕對應該添加更好的錯誤和邊緣情況處理,但希望這是一個有用的起點。
- 1 回答
- 0 關注
- 184 瀏覽
添加回答
舉報