(资料图片)

返回数据

在 Go-RESTful 中,可以使用 Response对象来返回数据。 Response对象有许多方法可用于设置响应头、状态码和响应正文。

以下是一个示例,演示如何返回 JSON 数据:

type Person struct {    Name string `json:"name"`    Age  int    `json:"age"`}func getPersonHandler(req *restful.Request, res *restful.Response) {    // 从数据库中获取 Person 对象    person := &Person{        Name: "Alice",        Age:  30,    }    res.WriteAsJson(person)}func main() {    ws := new(restful.WebService)    ws.Route(ws.GET("/people/{id}").To(getPersonHandler))    restful.Add(ws)    http.ListenAndServe(":8080", nil)}

在这个示例中,我们编写了一个名为 getPersonHandler的处理程序,它从数据库中获取一个名为 Alice、年龄为 30Person对象。然后,我们使用 res.WriteAsJson()方法将该对象作为 JSON 格式写入响应体中。

除了 JSON,还可以使用其他格式返回数据,例如 XML、HTML 或纯文本。以下是一个示例,演示如何返回 HTML:

func indexHandler(req *restful.Request, res *restful.Response) {    html := `                    Hello, world!                

Hello, world!

` res.Write([]byte(html))}func main() { ws := new(restful.WebService) ws.Route(ws.GET("/").To(indexHandler)) restful.Add(ws) http.ListenAndServe(":8080", nil)}

在这个示例中,我们编写了一个名为 indexHandler的处理程序,它返回一个包含简单 HTML 页面的字符串。然后,我们使用 res.Write()方法将该字符串作为 HTML 写入响应体中。

标签: