Golang的RESTful框架

Comments(16)


Posted on 2014-02-10 08:43:22 golang


Golang有自带的net/rpc和net/rpc/jsonrpc,前者是基于Gob编码协议的RPC,后者在前者基础上使用JSON编码。

在Python的世界,RESTful的框架比比皆是。由于Golang标准库没有自带,但有许多优秀的第三方库,例如下面要介绍的这个库,go-json-rest:

  • 基于net/http类型的Handler来实现,可以方便的和其他Handler合并。
  • 快速的URL路由。使用快速的字典树数据结构作为路由语法的实现。
  • 可访问/.status作为简单的监视。
  • 自带丰富的例子。

下面给出一个例子中的代码:

/* Demonstrate how to use rest.RouteObjectMethod

rest.RouteObjectMethod helps create a Route that points to
an object method instead of just a function.

The Curl Demo:

        curl -i -d '{"Name":"Antoine"}' http://127.0.0.1:8080/users
        curl -i http://127.0.0.1:8080/users/0
        curl -i -X PUT -d '{"Name":"Antoine Imbert"}' http://127.0.0.1:8080/users/0
        curl -i -X DELETE http://127.0.0.1:8080/users/0
        curl -i http://127.0.0.1:8080/users

*/
package main

import (
    "fmt"
    "github.com/ant0ine/go-json-rest"
    "net/http"
)

func main() {

    users := Users{
        Store: map[string]*User{},
    }

    handler := rest.ResourceHandler{
                EnableRelaxedContentType: true,
        }
    handler.SetRoutes(
        rest.RouteObjectMethod("GET", "/users", &users, "GetAllUsers"),
        rest.RouteObjectMethod("POST", "/users", &users, "PostUser"),
        rest.RouteObjectMethod("GET", "/users/:id", &users, "GetUser"),
        rest.RouteObjectMethod("PUT", "/users/:id", &users, "PutUser"),
        rest.RouteObjectMethod("DELETE", "/users/:id", &users, "DeleteUser"),
    )
    http.ListenAndServe(":8080", &handler)
}

type User struct {
    Id   string
    Name string
}

type Users struct {
    Store map[string]*User
}

func (self *Users) GetAllUsers(w *rest.ResponseWriter, r *rest.Request) {
    users := make([]*User, len(self.Store))
    i := 0
    for _, user := range self.Store {
        users[i] = user
        i++
    }
    w.WriteJson(&users)
}

func (self *Users) GetUser(w *rest.ResponseWriter, r *rest.Request) {
    id := r.PathParam("id")
    user := self.Store[id]
    if user == nil {
        rest.NotFound(w, r)
        return
    }
    w.WriteJson(&user)
}

func (self *Users) PostUser(w *rest.ResponseWriter, r *rest.Request) {
    user := User{}
    err := r.DecodeJsonPayload(&user)
    if err != nil {
        rest.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    id := fmt.Sprintf("%d", len(self.Store)) // stupid
    user.Id = id
    self.Store[id] = &user
    w.WriteJson(&user)
}

func (self *Users) PutUser(w *rest.ResponseWriter, r *rest.Request) {
    id := r.PathParam("id")
    if self.Store[id] == nil {
        rest.NotFound(w, r)
        return
    }
    user := User{}
    err := r.DecodeJsonPayload(&user)
    if err != nil {
        rest.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    user.Id = id
    self.Store[id] = &user
    w.WriteJson(&user)
}

func (self *Users) DeleteUser(w *rest.ResponseWriter, r *rest.Request) {
    id := r.PathParam("id")
    delete(self.Store, id)
}
前一篇: golang: 详解interface和nil 后一篇: fcntl的close-on-exec标志

Captcha:
验证码

Email:

Content: (Support Markdown Syntax)


pinnySot  2023-12-22 23:26:20 From 127.0.0.1

child labour in india essay in english https://buyessaysonlinedsd65432.aboutyoublog.com/23905063/top-latest-five-buy-essays-online-ds-d-urban-news writing an english essay


BFF 2 Person   2024-02-15 06:50:54 From 127.0.0.1

Embark on a journey of balance, trust, and shared wellness with BFF 2 Person Yoga Poses, a delightful fusion of friendship and fitness. These dynamic and engaging poses redefine the traditional yoga experience by inviting you and your best friend to join forces on the mat.


BFF 2 Person   2024-02-15 06:50:55 From 127.0.0.1

Embark on a journey of balance, trust, and shared wellness with BFF 2 Person Yoga Poses, a delightful fusion of friendship and fitness. These dynamic and engaging poses redefine the traditional yoga experience by inviting you and your best friend to join forces on the mat.


BFF 2 Person   2024-02-15 06:50:55 From 127.0.0.1

Embark on a journey of balance, trust, and shared wellness with BFF 2 Person Yoga Poses, a delightful fusion of friendship and fitness. These dynamic and engaging poses redefine the traditional yoga experience by inviting you and your best friend to join forces on the mat.


Angel Numbers  2024-02-15 11:00:44 From 127.0.0.1

Common examples of angel numbers include repeated sequences like 111, 222, 333, and so on. Each number is believed to carry a unique message or energy that can offer insights into different aspects of one’s life.


cryptoboss casino зеркало  2024-09-18 19:12:16 From 127.0.0.1

Заблокировано? Не беда! Находите актуальные зеркала Cryptoboss Casino здесь, прокачивайтесь без проблем! Самое актуальное зеркало Cryptoboss Casino всегда под рукой, полный контроль гарантированы. Лучшее зеркало Cryptoboss Casino ждет вас прямо сейчас, пропустите другие варианты! Проводите время с удовольствием на зеркале Cryptoboss Casino!, играйте и выигрывайте! Не забудьте использовать зеркало Cryptoboss Casino для безопасной игры, играйте без риска без лишних хлопот! криптобосс официальное зеркало криптобосс casino зеркало .