(資料圖片)

返回?cái)?shù)據(jù)

在 Go-RESTful 中,可以使用 Response對(duì)象來(lái)返回?cái)?shù)據(jù)。 Response對(duì)象有許多方法可用于設(shè)置響應(yīng)頭、狀態(tài)碼和響應(yīng)正文。

以下是一個(gè)示例,演示如何返回 JSON 數(shù)據(jù):

type Person struct {    Name string `json:"name"`    Age  int    `json:"age"`}func getPersonHandler(req *restful.Request, res *restful.Response) {    // 從數(shù)據(jù)庫(kù)中獲取 Person 對(duì)象    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)}

在這個(gè)示例中,我們編寫(xiě)了一個(gè)名為 getPersonHandler的處理程序,它從數(shù)據(jù)庫(kù)中獲取一個(gè)名為 Alice、年齡為 30Person對(duì)象。然后,我們使用 res.WriteAsJson()方法將該對(duì)象作為 JSON 格式寫(xiě)入響應(yīng)體中。

除了 JSON,還可以使用其他格式返回?cái)?shù)據(jù),例如 XML、HTML 或純文本。以下是一個(gè)示例,演示如何返回 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)}

在這個(gè)示例中,我們編寫(xiě)了一個(gè)名為 indexHandler的處理程序,它返回一個(gè)包含簡(jiǎn)單 HTML 頁(yè)面的字符串。然后,我們使用 res.Write()方法將該字符串作為 HTML 寫(xiě)入響應(yīng)體中。

標(biāo)簽: