Golang的RESTful框架

Comments(4)


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)


NXM9LbnYna  2016-12-30 05:24:27 From 188.143.232.27

You really saved my skin with this intfomaoirn. Thanks!


WMnMWBE1ur  2016-12-31 22:42:49 From 188.143.232.32

Wonderful extnalapion of facts available here. http://cizshndcb.com [url=http://trfwjan.com]trfwjan[/url] [link=http://rseiwyklgsf.com]rseiwyklgsf[/link]


hakG0LF9wDW  2017-01-05 10:47:11 From 188.143.232.32

http://erfolgreichekreditanfrage.pw/kredit-zinseszinsrechner-download-kostenlos-chip.html


Dennisfep  2017-02-24 17:36:57 From 93.170.130.95

Zhheherhrh eg egemtr hrggwe wes egemtrghdfbsgd rwtwrqw