首页后端开发GOGo-RESTful-设计API接口示例

Go-RESTful-设计API接口示例

时间2023-07-05 14:15:02发布访客分类GO浏览347
导读:示例下面给出一个完整的示例,演示如何在 Go-RESTful 中设计 API 接口。package main import ( "net/http" "github.com/emicklei/go-restful" ...

示例

下面给出一个完整的示例,演示如何在 Go-RESTful 中设计 API 接口。

package main

import (
    "net/http"

    "github.com/emicklei/go-restful"
)

type Book struct {

    ID     int    `json:"id"`
    Title  string `json:"title"`
    Author string `json:"author"`
}


var 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"}
,
}


func getBooksHandler(req *restful.Request, res *restful.Response) {

    res.WriteAsJson(books)
}


func getBookHandler(req *restful.Request, res *restful.Response) {

    id := req.PathParameter("id")
    for _, book := range books {

        if book.ID == id {

            res.WriteAsJson(book)
            return
        }

    }

    res.WriteErrorString(http.StatusNotFound, "Book not found")
}


func createBookHandler(req *restful.Request, res *restful.Response) {

    book := new(Book)
    err := req.ReadEntity(book)
    if err != nil {

        res.WriteError(http.StatusBadRequest, err)
        return
    }

    book.ID = len(books) + 1
    books = append(books, *book)
    res.WriteAsJson(book)
}


func updateBookHandler(req *restful.Request, res *restful.Response) {

    id := req.PathParameter("id")
    for i, book := range books {

        if book.ID == id {

            updatedBook := new(Book)
            err := req.ReadEntity(updatedBook)
            if err != nil {

                res.WriteError(http.StatusBadRequest, err)
                return
            }

            updatedBook.ID = book.ID
            books[i] = *updatedBook
            res.WriteAsJson(updatedBook)
            return
        }

    }

    res.WriteErrorString(http.StatusNotFound, "Book not found")
}


func deleteBookHandler(req *restful.Request, res *restful.Response) {

    id := req.PathParameter("id")
    for i, book := range books {

        if book.ID == id {

            books = append(books[:i], books[i+1:]...)
            res.WriteHeader(http.StatusNoContent)
            return
        }

    }

    res.WriteErrorString(http.StatusNotFound, "Book not found")
}


func main() {

    ws := new(restful.WebService)
    ws.Path("/books").
        Route(ws.GET("").To(getBooksHandler)).
        Route(ws.GET("/{
id}
").To(getBookHandler)).
        Route(ws.POST("").To(createBookHandler)).
        Route(ws.PUT("/{
id}
").To(updateBookHandler)).
        Route(ws.DELETE("/{
id}
").To(deleteBookHandler))
    restful.Add(ws)
    http.ListenAndServe(":8080", nil)
}

在这个示例中,我们定义了一个名为 Book 的结构体,表示书籍的属性。然后,我们定义了五个处理程序,分别用于获取所有书籍、获取指定 ID 的书籍、创建新的书籍、更新指定 ID 的书籍和删除指定 ID 的书籍。最后,我们将这些处理程序添加到 restful.WebService 中,并在端口 8080 上启动 HTTP服务器。

现在,我们可以通过以下 URL 访问这些 API:

  • 获取所有书籍:http://localhost:8080/books
  • 获取指定 ID 的书籍:http://localhost:8080/books/{ id}
  • 创建新的书籍:http://localhost:8080/books
  • 更新指定 ID 的书籍:http://localhost:8080/books/{ id}
  • 删除指定 ID 的书籍:http://localhost:8080/books/{ id}

例如,要获取 ID 为 1 的书籍,可以通过以下 URL 访问:

http://localhost:8080/books/1

如果成功,服务器将返回以下 JSON 格式的响应:

{

    "id": 1,
    "title": "The Go Programming Language",
    "author": "Alan A. A. Donovan and Brian W. Kernighan"
}

如果未找到书籍,服务器将返回 HTTP 状态码 404 Not Found。

如果要创建新的书籍,可以通过 POST 请求发送以下 JSON 格式的数据:

{

    "title": "The Art of Computer Programming",
    "author": "Donald E. Knuth"
}

然后,服务器将在响应中返回新创建的书籍,包括自动生成的 ID。

类似地,要更新现有的书籍,可以通过 PUT 请求发送以下 JSON 格式的数据:

{

    "title": "The Art of Computer Programming",
    "author": "Donald E. Knuth"
}
    

并在 URL 中指定要更新的书籍的 ID。

最后,要删除现有的书籍,可以通过 DELETE 请求在 URL 中指定要删除的书籍的 ID。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!

go

若转载请注明出处: Go-RESTful-设计API接口示例
本文地址: https://pptw.com/jishu/290356.html
Go-RESTful-设计API接口(二) 2022-04-25:给定两个长度为N的数组,a[]和b[] 也就是对于每个位置i来说,有a[i]和b[i]两个属性 i a[i] b[i] j a[j] b[

游客 回复需填写必要信息