为了账号安全,请及时绑定邮箱和手机立即绑定

如何发出带有多个参数的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 关注
  • 110 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信