Go语言作为一门高效且强大的编程语言,非常适合用于构建Web服务。在Go中处理HTTP GET和POST请求是非常常见的任务,下面将给出一些处理这两种请求类型的示例。
go复制代码
| package main | |
|---|---|
| import ( | |
| "fmt" | |
| "io/ioutil" | |
| "net/http" | |
| ) | |
| func main() { | |
| http.HandleFunc("/post", func(w http.ResponseWriter, r *http.Request) { | |
| // 确保处理的是POST请求 | |
| if r.Method == "POST" { | |
| // 读取请求体中的数据 | |
| body, err := ioutil.ReadAll(r.Body) | |
| if err != nil { | |
| http.Error(w, "Error reading request body", http.StatusInternalServerError) | |
| return | |
| } | |
| defer r.Body.Close() | |
| // 打印请求体中的数据 | |
| fmt.Printf("Received POST request with body: %s\n", string(body)) | |
| // 发送响应给客户端 | |
| fmt.Fprintf(w, "Received your POST request. This is the response!") | |
| } else { | |
| http.Error(w, "Invalid request method", http.StatusMethodNotAllowed) | |
| } | |
| }) | |
| fmt.Println("Server is running on port 8080") | |
| http.ListenAndServe(":8080", nil) | |
| } |
在上面的示例中,我们创建了一个处理POST请求的处理函数。它首先检查请求的方法是否为POST,然后读取请求体中的数据,并向客户端发送一个确认收到的响应。注意,在读取完请求体后,我们使用defer关键字来确保请求体被正确关闭,以避免资源泄漏。
通过结合这两个示例,你可以构建一个能够同时处理GET和POST请求的Go Web服务器。在实际应用中,你可能还需要处理其他类型的HTTP请求,如PUT、DELETE等,但处理它们的基本模式与处理GET和POST请求相似。