在golang中,可以通过使用http.ResponseWriter
来实现以HttpBody响应请求。
以下是一个简单的示例代码:
package main
import (
"encoding/json"
"net/http"
)
type Response struct {
Message string `json:"message"`
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
response := &Response{Message: "Hello World!"}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
})
http.ListenAndServe(":8080", nil)
}
在上面的示例中,我们定义了一个名为Response
的结构体,用于存储响应消息。然后,在处理请求时,我们创建了一个新的Response
对象,并将其编码为JSON格式并写入到http.ResponseWriter
对象中。
最后,我们使用http.ListenAndServe()
函数来启动HTTP服务器并监听指定端口(8080)上的请求。当有请求到达时,服务器将调用我们定义的处理函数,并返回以HttpBody形式响应客户端请求。
需要注意的是,在实际开发过程中,可能需要对错误进行处理和日志记录等操作。