如何设置 Web 服务器以在 Go 中执行 POST 请求?
How to set up web server to perform POST Request in Go?
我想使用以下代码在 Go 中执行 POST 请求:
package main
import (
"fmt"
"io/ioutil"
"net/http"
"strings"
)
func main() {
const myurl string = "http://localhost:8000/"
request := strings.NewReader(`
{
"Name":"Tom",
"Age":"20"
}
`)
response, _ := http.Post(myurl, "application/json", request)
content, _ := ioutil.ReadAll(response.Body)
fmt.Println(string(content))
defer response.Body.Close()
}
但我不确定如何启动 Web 服务器来执行 POST 请求,这是我在 Visual Studio 代码的另一个选项卡中所做的实现:
package main
import (
"log"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request){})
log.Fatal(http.ListenAndServe(":8000", nil))
}
我缺少什么才能执行 POST 请求?
编辑:我在 VSCode 中将所有内容都放在一个选项卡中并进行了必要的更改,但是 post 请求如何执行,因为在 main 函数中只定义了 HandleFunc 和 ListenAndServe?
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))
}
这是一个基本示例,说明您可以如何着手。我对服务器和客户端都使用相同的程序运行。这仅用于演示目的。你当然可以把它们做成单独的程序。
// 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
}
我想使用以下代码在 Go 中执行 POST 请求:
package main
import (
"fmt"
"io/ioutil"
"net/http"
"strings"
)
func main() {
const myurl string = "http://localhost:8000/"
request := strings.NewReader(`
{
"Name":"Tom",
"Age":"20"
}
`)
response, _ := http.Post(myurl, "application/json", request)
content, _ := ioutil.ReadAll(response.Body)
fmt.Println(string(content))
defer response.Body.Close()
}
但我不确定如何启动 Web 服务器来执行 POST 请求,这是我在 Visual Studio 代码的另一个选项卡中所做的实现:
package main
import (
"log"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request){})
log.Fatal(http.ListenAndServe(":8000", nil))
}
我缺少什么才能执行 POST 请求?
编辑:我在 VSCode 中将所有内容都放在一个选项卡中并进行了必要的更改,但是 post 请求如何执行,因为在 main 函数中只定义了 HandleFunc 和 ListenAndServe?
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))
}
这是一个基本示例,说明您可以如何着手。我对服务器和客户端都使用相同的程序运行。这仅用于演示目的。你当然可以把它们做成单独的程序。
// 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
}