zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Go-RESTful-设计API接口(二)

2023-06-13 09:18:56 时间

数据格式

在设计 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 响应中。