2014-12-02 58 views
0
發送POST請求

我試圖用這個函數來發送POST請求 - {得到一個錯誤的迴應 - 從服務器422,而在GO

func (Client *Client) doModify(method string, url string, createObj interface{}, respObject interface{}) error { 

    bodyContent, err := json.Marshal(createObj) 
    if err != nil { 
     return err 
    } 

    client := Client.newHttpClient() 

    req, err := http.NewRequest(method, url, bytes.NewBuffer(bodyContent)) 
    if err != nil { 
     return err 
    } 

    Client.setupRequest(req) 
    req.Header.Set("Content-Type", "application/json") 
    req.Header.Set("Content-Length", string(len(bodyContent))) 

    resp, err := client.Do(req) 

    if err != nil { 
     return err 
    } 

    defer resp.Body.Close() 

    if resp.StatusCode >= 300 { 
     return errors.New(fmt.Sprintf("Bad response from [%s], go [%d]", url, resp.StatusCode)) 
    } 

    byteContent, err := ioutil.ReadAll(resp.Body) 
    if err != nil { 
     return err 
    } 

    return json.Unmarshal(byteContent, respObject) 
} 

}

我打電話給我的功能這樣的 -

{

func TestContainerCreate(t *testing.T) { 
    client := newClient(t) 
    container, err := client.Container.Create(&Container{ 
     Name:  "name", 
     ImageUuid: "xyz", 
    }) 

    if err != nil { 
     t.Fatal(err) 
    } 

    defer client.Container.Delete(container) 

} 

}

Create函數在內部調用調用doCreate函數,該函數調用粘貼在頂部的doModify函數。 {

func (self *ContainerClient) Create(container *Container) (*Container, error) { 
    resp := &Container{} 
    err := self.Client.doCreate(container_TYPE, container, resp) 
    return resp, err 
} 

}

{

func (Client *Client) doCreate(schemaType string, createObj interface{}, respObject interface{}) error { 
     if createObj == nil { 
      createObj = map[string]string{} 
     } 

     schema, ok := Client.Types[schemaType] 
     if !ok { 
      return errors.New("Unknown schema type [" + schemaType + "]") 
     } 

     return Client.doModify("POST", collectionUrl, createObj, respObject) 
    } 

}

這給了我422壞response.On做進一步的研究,在做捲曲,用 「名」 和「imageUuid」的第一個字母爲小寫,給出了201創建的狀態,但當通過「Name」和「ImageUuid」的第一個字母時,由於資本給出了422壞響應。可以有與容器定義的json結構的問題,或這些實體被定義或其他的情況? {

curl -X POST -v -s http://localhost:8080/v1/containers -H 'Content-Type: application/json' -d '{"name" : "demo", "imageUuid" : "docker:nginx"}' | python -m 'json.tool' 

}

集裝箱結構的定義是這樣的 - {

type Container struct { 
    Resource 

    ImageId string `json:"ImageId,omitempty"` 

    ImageUuid string `json:"ImageUuid,omitempty"` 

    MemoryMb int `json:"MemoryMb,omitempty"` 

    Name string `json:"Name,omitempty"` 

} 

type ContainerCollection struct { 
    Collection 
    Data []Container `json:"data,omitempty"` 
} 

}

+0

什麼是您編組json的結構定義? – JimB 2014-12-02 19:07:09

+0

剛剛在上面提供的內容中添加/編輯了結構定義。 – psbits 2014-12-02 19:15:15

+0

所以如果大寫字母不起作用,爲什麼不把它們變成小寫字母呢? – JimB 2014-12-02 19:17:51

回答

3

string(len(bodyContent))沒有做什麼,你認爲它是。你將一個int轉換爲一個utf-8字符串。您想使用strconv包來獲取數字表示。

另請注意,由於0是一個有效值,因此不能使用omitempty

+0

很好的抓住一堆代碼! – Volker 2014-12-02 21:07:15

相關問題