问题描述
使用单个API资源/
,我们仅编写了一个处理程序来处理API资源GET
上的POST
和/
请求
POST
我们用来在数据库中创建资源,通过在请求正文中发送数据
PUT
,我们用来更新数据库中的现有资源
RESTful最佳实践表示,我的理解是,处理程序需要为所有请求/
,GET
和POST
的API资源(例如PUT
)提供服务>
我们希望同一个处理程序处理PUT
请求,但API资源将类似于/1234
,其中1234
是现有ID
从技术上讲,API资源/1234
也将映射到处理/
的同一处理程序,但是
根据RESTful最佳实践,是否需要处理/1234
而不将ID作为API资源URI的一部分传递?像下面这样...
func ServeHTTP(w http.ResponseWriter,r *http.Request) {
if r.Method == http.MethodGet { // for API resource '/'
p.getProducts(w,r)
return
}
if r.Method == http.MethodPost { // for API resource '/'
p.addProduct(w,r)
return
}
if r.Method == http.MethodPut { // for API resource '/'
p.updateProduct(w,r)
return
}
}
func updateProduct(w http.ResponseWriter,r *http.Request) {
var idString string
decoder := json.NewDecoder(r.Body)
decoder.Decode(idString)
id,err := findID(idString)
// do whatever with id
}
func findID(str string) (int,error) {
dfa := regexp.MustCompile(`/([0-9]+)`)
matches := dfa.FindAllStringSubmatch(str,-1) // returns [][]string
idString := matches[0][1]
id,err := strconv.Atoi(idString)
return id,nil
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)