2017-10-08 112 views
0

我在我的应用程序中有产品和项目。产品是项目的集合。例如,T恤是一种产品,它具有尺寸和颜色等属性。尺寸为S,M,L,XL,颜色为红色,绿色和蓝色。使用http包实现REST多个资源和标识符

我想使用http包仅用于构建REST服务。 (No Gorilla Mux,Goji等)。

POST API添加产品

http://localhost/product 

针对上述情况,我用

http.HandleFunc("/product", AddProduct) 

func AddProduct(w http.ResponseWriter, r *http.Request) { 
    if r.Method == "POST" { 
    // My code 
    } 
} 

我想知道如何实现以下内容:

GET API来获取特定产品的物品清单

http://localhost/product/23 

POST API来在产品中添加项目

http://localhost/product/23/item 

GET API返回项目详细

http://localhost/product/23/item/4 

注:我一直在寻找的堆栈溢出了2个多小时,并不能找到相关答案。如果这已经被问到,我真的很抱歉...请在评论中提供链接。

回答

1

下应该给你一个起点,从工作:

package main 

import (
    "log" 
    "strconv" 
    "net/http" 
    "strings" 
) 

func AddProduct(w http.ResponseWriter, r *http.Request) { 
    c := strings.Split(strings.Trim(r.URL.Path, "/"), "/") 
    switch { 
    case len(c) == 2: 
     // GET product/{id} 
     if r.Method != "GET" && r.Method != "HEAD" { 
      http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) 
      return 
     } 
     id, err := strconv.Atoi(c[1]) 
     if err != nil { 
      break 
     } 
     // implementation 
     return 

    case len(c) == 3 && c[2] == "item": 
     // POST product/{id}/item 
     if r.Method != "POST" { 
      http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) 
      return 
     } 
     id, err := strconv.Atoi(c[1]) 
     if err != nil { 
      break 
     } 
     // implementation 
     return 

    case len(c) == 4 && c[2] == "item": 
     // GET product/{id}/item/{itemID} 
     if r.Method != "GET" && r.Method != "HEAD" { 
      http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) 
      return 
     } 
     id, err := strconv.Atoi(c[1]) 
     if err != nil { 
      break 
     } 

     itemID, err := strconv.Atoi(c[3]) 
     if err != nil { 
      break 
     } 
     // implementation 
     return 
    } 
    http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound) 
} 

func main() { 
    http.HandleFunc("/product/", AddProduct) 
    log.Fatal(http.ListenAndServe(":8080", nil)) 
} 
相关问题