Rest 如何使用多个参数发出post请求

Rest 如何使用多个参数发出post请求,rest,go,Rest,Go,在使用标准库的Go中,我如何发出POST请求,在网页上输入多个参数并输出信息 i、 e 用户输入姓名和喜爱的爱好 名称: 爱好: 提交(按钮) 然后网页更新并显示 您的姓名是(姓名),您喜欢(爱好)您可以使用Go标准库中的软件包来完成此操作 这里的基本过程是: 编写模板(使用go/HTML模板语言) 读入模板(使用template.ParseFiles或类似工具) 倾听请求 将相关请求中的信息传递给模板(使用ExecuteTemplate或类似工具) 您可以将结构传递给ExecuteTempla

在使用标准库的Go中,我如何发出POST请求,在网页上输入多个参数并输出信息

i、 e

用户输入姓名和喜爱的爱好

名称

爱好

提交(按钮)

然后网页更新并显示

您的姓名是(姓名),您喜欢(爱好)

您可以使用Go标准库中的软件包来完成此操作

这里的基本过程是:

  • 编写模板(使用go/HTML模板语言)
  • 读入模板(使用
    template.ParseFiles
    或类似工具)
  • 倾听请求
  • 将相关请求中的信息传递给模板(使用
    ExecuteTemplate
    或类似工具)
  • 您可以将结构传递给
    ExecuteTemplate
    ,然后可以在您定义的模板中访问该结构(参见下面的示例)。例如,如果您的结构有一个名为
    Name
    的字段,则可以使用
    {{.Name}
    在模板中访问此信息

    以下是一个示例:

    main.go

    <!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>
    
    包干管

    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>
    
    答复:

    <!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>
    
    
    你的名字是
    艾哈迈德
    你的爱好是
    脱毛
    

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

    您尝试了什么?包括你的代码。你遇到了什么问题?