用 Go 语言编写 RESTful API

github.com/drone/routes 资源给出了一个简单的 REST 框架,因为 Go 语言提供了非常方便的内置 HTTP 框架,所以自己写一个这样的框架应该不困难,这里是我做的读书和试验笔记,留着做个参考。

下面是我摘录的部分代码:

package main
import (
    "fmt"
    "net/http"
    "github.com/drone/routes"
)
func getroute(w http.ResponseWriter, r *http.Request) {
    params := r.URL.Query()
    uid := params.Get(":uid")
    fmt.Fprintf(w, "you are get user %s", uid)
}

... ...
func run() {
    mux := routes.New()
    mux.Get("/user/:uid", getroute)
    mux.Put("/user/", putroute)
    http.Handle("/", mux)
    http.ListenAndServe(":8080", nil)
    fmt.Println("restful server is stopped !!!")
}
... ...

这里有一个特别之处需要提醒,REST 的命令参数传递有两种选择:

  • 一种是利用 “/” 传递,例如用户LiMIng的密码是123456,其登录URL可能是这种形式:“http://…./identification/LiMing/123456”。
  • 另一种是利用“?”分割参数,上面的例子 URL 可能会写成如下形式:“http://…./identification?name=LiMing&password=123456

    drone 这个框架采用的是第一种形式,感觉这种形式的工作效率可能要高一些,貌似 Go 的 HTTP 框架就是支持这种形式。如果有多个参数,可以按照以下格式编写:

mux.Get("/user/:uid/:password", getroute)

猜你喜欢

转载自blog.csdn.net/quicmous/article/details/79776416
今日推荐