当前位置: 首页 > 滚动 > >正文

热资讯!Go-RESTful-设计API接口(二)

来源:腾讯云    时间:2023-04-28 11:32:22


(相关资料图)

数据格式

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

X 关闭

推荐内容

最近更新

Copyright ©  2015-2022 南方洁具网  版权所有    
备案号:粤ICP备18023326号-21     
 联系邮箱:855 729 8@qq.com