簡體   English   中英

如何設置 web 服務器在 Go 中執行 POST 請求?

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

我想設置一個 web 服務器來執行 POST 請求。 由於主 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))
}

這是一個基本示例,說明如何使用 go。 我使用相同的程序來運行服務器和客戶端。 這僅用於演示目的。 您當然可以使它們成為單獨的程序。

// 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
}

這是工作示例: https://go.dev/play/p/34GT04jy_uA

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM