net/http包如何实现restful api?

jinwangdalaohu · 2016-10-05 13:06:05 · 4121 次点击 · 大约8小时之前 开始浏览    置顶
这是一个创建于 2016-10-05 13:06:05 的主题,其中的信息可能已经有所发展或是发生改变。

http.HandleFunc("/hello/", hello.Hello)

请不要推荐第三方包

如上所示,net/http建立一个简单的路由来处理http请求。但是要实现restful API,要怎么写呢? http://127.0.0.1:8080/hello get post delete modify这种


有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

4121 次点击  
加入收藏 微博
5 回复  |  直到 2016-10-07 05:53:37
brucelandor
brucelandor · #1 · 9年之前
switch req.Method {
case http.MethodGet:
// deal with GET
case http.MethodPost:
// deal with POST
// ...
}
brucelandor
brucelandor · #2 · 9年之前

或者if else

jinwangdalaohu
jinwangdalaohu · #3 · 9年之前
brucelandorbrucelandor #1 回复

``` switch req.Method { case http.MethodGet: // deal with GET case http.MethodPost: // deal with POST // ... } ```

这样写也是可以,不过有点重复性太大

jinwangdalaohu
jinwangdalaohu · #4 · 9年之前

看了net/http包的server.go源代码里,里面有个conn结构体对应的接口ServeHTTP,实现这个接口,在这个接口里对URL和方法进行映射应该就能实现restful

brucelandor
brucelandor · #5 · 9年之前
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传