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合并。下面给出一个例子中的代码:
/* 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)
}
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
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.
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.
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.
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 здесь, прокачивайтесь без проблем! Самое актуальное зеркало Cryptoboss Casino всегда под рукой, полный контроль гарантированы. Лучшее зеркало Cryptoboss Casino ждет вас прямо сейчас, пропустите другие варианты! Проводите время с удовольствием на зеркале Cryptoboss Casino!, играйте и выигрывайте! Не забудьте использовать зеркало Cryptoboss Casino для безопасной игры, играйте без риска без лишних хлопот! криптобосс официальное зеркало криптобосс casino зеркало .