【資料圖】
數據格式
在設計 API 接口時,需要考慮如何表示數據。通常,數據應該表示為資源的表示形式,例如 JSON 或 XML。以下是一個示例,演示如何使用 JSON 表示數據:
type Book struct { ID int `json:"id"` Title string `json:"title"` Author string `json:"author"`}func getBooksHandler(req *restful.Request, res *restful.Response) { books := []Book{ {ID: 1, Title: "The Go Programming Language", Author: "Alan A. A. Donovan and Brian W. Kernighan"}, {ID: 2, Title: "Effective Go", Author: "The Go Authors"}, } res.WriteAsJson(books)}func main() { ws := new(restful.WebService) ws.Route(ws.GET("/books").To(getBooksHandler)) restful.Add(ws) http.ListenAndServe(":8080", nil)}
在這個示例中,我們編寫了一個名為 Book 的結構體,表示書籍的屬性。然后,我們編寫了一個名為 getBooksHandler 的處理程序,返回一個包含兩本書籍的數組。最后,我們使用 res.WriteAsJson()將書籍數組作為 JSON 格式寫入 HTTP 響應中。