如何使用标准库在Go中发出POST请求以在网页上接收多个参数并输出信息。
即
用户输入名称和喜欢的爱好
名称:
业余爱好:
提交(按钮)
然后网页更新和显示
您的姓名为(姓名),而您想(爱好)
答案 0 :(得分:2)
您可以使用Go标准库中的html/template软件包进行此操作。
这里的基本过程是:
template.ParseFiles
或类似方法ExecuteTemplate
或类似方法)您可以将结构传递给ExecuteTemplate
,然后可以在您定义的模板中对其进行访问(请参见下面的示例)。例如,如果您的结构具有一个名为Name
的字段,那么您可以使用{{ .Name }}
在模板中访问此信息。
以下是示例:
<强> main.go 强>:
软件包主要
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)
}
<强> index.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>
请注意,这非常脆弱,因此您绝对应该添加更好的错误和边缘情况处理,但是希望这是一个有用的起点。