当前位置: 首页 > 工具软件 > go-restful > 使用案例 >

go-restful实战与深入分析之使用篇

暨高洁
2023-12-01
原文地址为: go-restful实战与深入分析之使用篇

go的rest框架很多国内最著名应该是beego,但这个框架设计思想比较老套而且很笨重,如果需要一个轻量级的框架我个人挺喜欢go-restful先看看怎么使用,如果有过Flask或者springMVC的经验,这个很容易上手,所以我个人觉得语言是想通的,先学好一门语言其它的按照套路来就可以了,先看代码例子:

package main

import (
    "log"
    "net/http"

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

// This example has the same service definition as restful-user-resource
// but uses a different router (CurlyRouter) that does not use regular expressions
//
// POST http://localhost:8080/users
// <User><Id>1</Id><Name>Melissa Raspberry</Name></User>
//
// GET http://localhost:8080/users/1
//
// PUT http://localhost:8080/users/1
// <User><Id>1</Id><Name>Melissa</Name></User>
//
// DELETE http://localhost:8080/users/1
//

type User struct {
    Id, Name string
}

type UserResource struct {
    // normally one would use DAO (data access object)
    users map[string]User
}

func (u UserResource) Register(container *restful.Container) {
    ws := new(restful.WebService)
    ws.
    Path("/users").
        Consumes(restful.MIME_XML, restful.MIME_JSON).
        Produces(restful.MIME_JSON, restful.MIME_XML) // you can specify this per route as well

    ws.Route(ws.GET("/{user-id}").To(u.findUser))
    ws.Route(ws.POST("").To(u.updateUser))
    ws.Route(ws.PUT("/{user-id}").To(u.createUser))
    ws.Route(ws.DELETE("/{user-id}").To(u.removeUser))

    container.Add(ws)
}

// GET http://localhost:8080/users/1
//
func (u UserResource) findUser(request *restful.Request, response *restful.Response) {
    id := request.PathParameter("user-id")
    usr , ok := u.users[id]
    if !ok {
        response.AddHeader("Content-Type", "text/plain")
        response.WriteErrorString(http.StatusNotFound, "User could not be found.")
    } else {
        response.WriteEntity(usr)
    }
}

// POST http://localhost:8080/users
// <User><Id>1</Id><Name>Melissa Raspberry</Name></User>
//
func (u *UserResource) updateUser(request *restful.Request, response *restful.Response) {
    usr := new(User)
    err := request.ReadEntity(&usr)
    if err == nil {
        u.users[usr.Id] = *usr
        response.WriteEntity(usr)
    } else {
        response.AddHeader("Content-Type", "text/plain")
        response.WriteErrorString(http.StatusInternalServerError, err.Error())
    }
}

// PUT http://localhost:8080/users/1
// <User><Id>1</Id><Name>Melissa</Name></User>
//
func (u *UserResource) createUser(request *restful.Request, response *restful.Response) {
    usr := User{Id: request.PathParameter("user-id")}
    err := request.ReadEntity(&usr)
    if err == nil {
        u.users[usr.Id] = usr
        response.WriteHeaderAndEntity(http.StatusCreated, usr)
    } else {
        response.AddHeader("Content-Type", "text/plain")
        response.WriteErrorString(http.StatusInternalServerError, err.Error())
    }
}

// DELETE http://localhost:8080/users/1
//
func (u *UserResource) removeUser(request *restful.Request, response *restful.Response) {
    id := request.PathParameter("user-id")
    delete(u.users, id)
}

func main() {
    wsContainer := restful.NewContainer()
    wsContainer.Router(restful.CurlyRouter{})
    u := UserResource{map[string]User{}}
    u.Register(wsContainer)

    log.Printf("start listening on localhost:8080")
    server := &http.Server{Addr: ":8080", Handler: wsContainer}
    log.Fatal(server.ListenAndServe())
}

代码很简单,users的一套CURD。这里面有几个点说一下,首先需要定义一个web container的容器wsContainer,然后把webservice放到容器里面,可以理解成一个container里面有很多的webservice,每个webservice里面有先定义Path路径,在这里面是/users,在这个路径下面会有CURD的方法,通过Route去确定方法匹配和跳转。启动上面代码就可以测试了,先测试一个创建:

POST
127.0.0.1:8080/users
{
"Id":"43a",
"Name":"eee"
}

再测试一个查询

GET
127.0.0.1:8080/users/43a

当然我不想止步于此,具体看看这个go-restful是怎样实现的。


转载请注明本文地址: go-restful实战与深入分析之使用篇
 类似资料: