简体   繁体   English

如何设置 web 服务器在 Go 中执行 POST 请求?

[英]How to set up web server to perform POST Request in Go?

I want to set up a web server to perform a POST request.我想设置一个 web 服务器来执行 POST 请求。 How does the post request get executed with the code below since only HandleFunc and ListenAndServe are defined in main function?由于主 function 中仅定义了 HandleFunc 和 ListenAndServe,因此如何使用以下代码执行 post 请求?

package main

import (
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
 )

func post(w http.ResponseWriter, r *http.Request) {
  const myurl string = "http://localhost:8000/"
  request := strings.NewReader(`
  {
    "Name":"Tom",
    "Age":"20" 
  }
`)
  response, err := http.Post(myurl, "application/json", request)
  content, err := ioutil.ReadAll(response.Body)
  if err != nil {
     panic(err)
  }
  fmt.Println(string(content))
  defer response.Body.Close()
  }
func main() {
  http.HandleFunc("/", post)
  log.Fatal(http.ListenAndServe(":8000", nil))
}

Here is a basic example of how you could go about it.这是一个基本示例,说明如何使用 go。 I am using the same program to run both, the server and the client.我使用相同的程序来运行服务器和客户端。 This is just for demonstration purposes.这仅用于演示目的。 You can of course make them separate programs.您当然可以使它们成为单独的程序。

// use struct to represent the data 
// to recieve and send
type Person struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}
// run the example
func main() {
    // start the server in a goroutine
    go server()

    // wait 1 second to give the server time to start
    time.Sleep(time.Second)

    // make a post request
    if err := client(); err != nil {
        fmt.Println(err)
    }
}
// basic web server to receive a request and 
// decode the body into a user struct
func server() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        if r.Method != http.MethodPost  {
            http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
            return
        }

        user := &Person{}
        err := json.NewDecoder(r.Body).Decode(user)
        if err != nil {
            http.Error(w, err.Error(), http.StatusBadRequest)
            return
        }

        fmt.Println("got user:", user)
        w.WriteHeader(http.StatusCreated)
    })

    if err := http.ListenAndServe(":8080", nil); err != http.ErrServerClosed {
        panic(err)
    }
}
// a simple client that posts a user to the server
func client() error {
    user := &Person{
        Name: "John",
        Age:  30,
    }

    b := new(bytes.Buffer)
    err := json.NewEncoder(b).Encode(user)
    if err != nil {
        return err
    }

    resp, err := http.Post("http://localhost:8080/", "application/json", b)
    if err != nil {
        return err
    }
    defer resp.Body.Close()

    fmt.Println(resp.Status)
    return nil
}

Here is the working example: https://go.dev/play/p/34GT04jy_uA这是工作示例: https://go.dev/play/p/34GT04jy_uA

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Go 中重用 HTTP 请求实例 - How to reuse HTTP request instance in Go 如何正确解组/解析使用 Go 的请求? - How to unmarshal/parse a request using Go correctly? 如何在 Go 结构中设置默认值 - How to set default values in Go structs HTTP 发布 API 请求,使用 go 语言和 AWS 机密管理器 Z099FB995346F31C749F6E0E4 - HTTP Post API request using go lang with aws secrets manager header 如何在 go redis 客户端中使用 igbinary 序列化 GET 和 SET - How to serialize GET and SET using igbinary inside go redis client Go 如何处理 Google App Engine 上的并发请求 - How does Go handle concurrent request on Google App Engine 如何设置 AWS Cloud9 以使用 webpack-dev-server(在开发模式下)运行现有的 JavaScript 应用程序? - How do I set up AWS Cloud9 to run an existing JavaScript app with webpack-dev-server (in development mode)? GO:我如何使用 go 反射来设置结构指针的值 - GO: how can i use go reflect to set the value of pointer of struct 如何使用 firebase 云消息和云功能设置推送通知? - How can I go about setting up push notifications using firebase cloud messaging and cloud functions? Nodejs Post 请求在 Postman 中不起作用? - Nodejs Post request is not working in Postman?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM