(資料圖片)
返回數(shù)據(jù)
在 Go-RESTful 中,可以使用 Response對象來返回數(shù)據(jù)。 Response對象有許多方法可用于設(shè)置響應(yīng)頭、狀態(tài)碼和響應(yīng)正文。
以下是一個示例,演示如何返回 JSON 數(shù)據(jù):
type Person struct { Name string `json:"name"` Age int `json:"age"`}func getPersonHandler(req *restful.Request, res *restful.Response) { // 從數(shù)據(jù)庫中獲取 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的處理程序,它從數(shù)據(jù)庫中獲取一個名為 Alice、年齡為 30的 Person對象。然后,我們使用 res.WriteAsJson()方法將該對象作為 JSON 格式寫入響應(yīng)體中。
除了 JSON,還可以使用其他格式返回數(shù)據(jù),例如 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 寫入響應(yīng)體中。
標(biāo)簽:
營業(yè)執(zhí)照公示信息