2017-10-08 24 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)) 
} 
相關問題