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)


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


SlireeSop  2021-06-18 09:04:55 From 127.0.0.1

by prednisone w not prescription


Ernestoken  2021-08-10 02:47:25 From 127.0.0.1

coupons for sildenafil viagra pills non prescription viagra viagra best buy sildenafil tablets uk sildenafil tablets 150mg


Stromectol  2021-11-12 15:00:07 From 127.0.0.1

softtabs cialis


combape  2022-09-13 13:48:04 From 127.0.0.1

hair loss with tamoxifen Most fertility centers have a criteria that determines when they will cancel the IVF process before egg retrieval.


blareenda  2023-01-31 09:40:04 From 127.0.0.1

244 anaesth or anesth or ante natal or antenatal or bleeding or caesarean or cesarean or caesarian or cesarian or caesarien or cesarien or cirrho or eclamp or epidural or fetal or foetal or fetus or foetus or gestational hypertens or glaucom or interocular or intraocular or intracran or intuba or lactation or neonat or new born or newborn or obstetr or ocular or ophthalm or peri partum or peripartum or portal hypertens or portopulmonary or pre eclamp or preeclamp or pregnancies or pregnancy or pregnant or pre natal or prenatal or pulmonary hypertens or pulmonary arterial hypertens or secondary hypertens or spinal long term use of clomid in males 8 and 5 females 15


Lourdessnirl  2023-12-05 14:33:22 From 127.0.0.1

online gambling casino paypal online casino blackjack game casino games sites best slot machine apps for android keno online indonesia keno online betting internet casino keno online casinos deposit methods