亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何發出帶有多個參數的post請求

如何發出帶有多個參數的post請求

Go
慕婉清6462132 2023-06-05 17:07:37
我如何使用標準庫在 Go 中發出 POST 請求以接收多個參數并在網頁上輸出信息。IE用戶輸入姓名和最喜歡的愛好姓名:愛好:提交(按鈕)然后網頁更新并顯示你的名字是(姓名),你喜歡(愛好)
查看完整描述

1 回答

?
天涯盡頭無女友

TA貢獻1831條經驗 獲得超9個贊

您可以使用Go 標準庫中的html/template包來執行此操作。

這里的基本流程是:

  1. 編寫模板(go/HTML模板語言)

  2. 閱讀模板(使用template.ParseFiles或類似)

  3. 監聽請求

  4. 將相關請求中的信息傳遞到您的模板(使用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>

請注意,這是非常脆弱的,因此您絕對應該添加更好的錯誤和邊緣情況處理,但希望這是一個有用的起點。


查看完整回答
反對 回復 2023-06-05
  • 1 回答
  • 0 關注
  • 184 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號