帮我go开发一个小程序能够接收消息返回结果
好的,以下是一个简单的Go程序,可以接收消息并返回结果:
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
func handler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
message := r.FormValue("message")
fmt.Fprintf(w, "Received message: %s", message)
} else {
fmt.Fprintf(w, "Hello, World!")
}
}
这个程序会监听8080端口,当接收到HTTP请求时,如果是POST请求,就从请求参数中获取"message"参数的值,并返回"Received message: "加上这个值;否则,就返回"Hello, World!"。你可以使用POST请求来发送消息给这个程序,例如:
curl -X POST -d "message=Hello, Go!" http://localhost:8080/
这个命令会向http://localhost:8080/发送一个POST请求,请求参数中包含"message"参数,它的值是"Hello, Go!"。你会得到以下响应:
Received message: Hello, Go!
希望这个程序能够帮到你。
原文地址: https://www.cveoy.top/t/topic/npQ 著作权归作者所有。请勿转载和采集!