我想用一個簡單的Go(go1.8 darwin/amd64)程序打一個Java Spring Boot應用程序提供的REST端點。我試圖打在2種獨立的方式:403製作Golang POST時禁止
const (
LOCAL_BASE = "http://localhost:11400"
ADD_FUNDS_ENDPOINT = "/sub-accounts/%d/add-funds"
)
type InputArgumentsJson struct {
Amount float64 `json:"amount"`
BufferAmount float64 `json:"bufferAmount"`
FromSubAccountID int `json:"fromSubAccountId"`
}
...
// set up json body
inputArguments := &InputArgumentsJson{Amount: 1100, BufferAmount: 0,
FromSubAccountID: spendFundId}
bytes := new(bytes.Buffer)
json.NewEncoder(bytes).Encode(inputArguments)
// set up the url to call
endpoint := fmt.Sprintf(ADD_FUNDS_ENDPOINT, billSetAsideId)
url := LOCAL_BASE + endpoint
client := &http.Client{}
req, err := http.NewRequest("POST", url, bytes)
if err != nil {
fmt.Println("ERROR WHILE BUILDING REQUEST")
fmt.Println(err)
}
req.Header.Add("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
fmt.Println("ERROR WHILE MAKING REQUEST")
fmt.Println(err)
}
fmt.Println(resp)
和:
resp, err := http.Post(url, "application/json; charset=utf-8", bytes)
if err != nil {
fmt.Println("ERROR WHILE MAKING REQUEST")
fmt.Println(err)
}
fmt.Println(resp)
我增加了打印出來,看看URL和JSON的身體是正確的,他們似乎是:
fmt.Printf("\nMaking request to %s with:\n %s\n", url, bytes)
打印出來
Making request to http://localhost:11400/sub-accounts/167/add-funds with:
{"amount":1100,"bufferAmount":0,"fromSubAccountId":166}
,但運行時我得到了403禁止。
我可以打這個端點沒有失敗同時使用郵差和下面的curl命令:
curl -H "Content-Type: application/json" -X POST -d '{"amount":1100,"bufferAmount":0,"fromSubAccountId":166}' http://localhost:11400/sub-accounts/167/add-funds
有沒有人有什麼我可以在這裏失蹤的任何想法?爲了進一步增加趣味,我可以成功地從Go程序中創建不同的GET端點。
在此先感謝!
編輯以表明我捕捉錯誤和周圍的邏輯創建URL和JSON身體
嘗試在您的請求和響應中首先發現錯誤'resp,err:= client.Do(req)'。 – Elad
我實際上是這樣捕捉它們,然後用'if er!= nil'來打印出來,但沒有任何東西被捕獲。爲了簡潔起見,我把它留下了,因爲服務器明顯在響應,但是有一個403. –