如何使多个参数的post请求

时间:2019-02-02 19:21:44

标签: rest go

如何使用标准库在Go中发出POST请求以在网页上接收多个参数并输出信息。

用户输入名称和喜欢的爱好

名称

业余爱好

提交(按钮)

然后网页更新和显示

您的姓名为(姓名),而您想(爱好)

1 个答案:

答案 0 :(得分:2)

您可以使用Go标准库中的html/template软件包进行此操作。

这里的基本过程是:

  1. 撰写模板(在去/ HTML模板语言)
  2. 读入模板(使用template.ParseFiles或类似方法
  3. 听请求
  4. 将相关请求中的信息传递到您的模板(使用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>

请注意,这非常脆弱,因此您绝对应该添加更好的错误和边缘情况处理,但是希望这是一个有用的起点。