我目前遇到一个真正让我感到沮丧的问题,我绝对看不到我的代码有任何问题。


我想要实现的是将 http POST 消息发送到我编写的 iDrac 模型(这两个软件都是用 golang 编写的)以控制模型的电源状态,但无论我为请求配置什么,模型总是收到 get带有空体的请求。


我创建并发送请求的功能:


func (iDrac *IDrac) SetPowerstate(powerstate string) error {


    //Create reset type json string

    var jsonStr = `{"ResetType":"` + powerstate + `"}`


    //Create the request with auth header

    req, reqErr := iDrac.buildHttpRequestWithAuthorizationHeader(http.MethodPost, "https://"+iDrac.hostAddress+apiBaseURL+apiChassisURL+apiChassisResetAction, jsonStr)

    if reqErr != nil {

        return fmt.Errorf("COULD_NOT_CREATE_REQUEST: " + reqErr.Error())

    }

    req.Header.Set("Content-Type", "application/json; charset=UTF-8")


    //Make the request

    resp, doErr := http.DefaultClient.Do(req)

    if doErr != nil {

        return fmt.Errorf("COULD_NOT_SEND_POST_REQUEST_TO_IDRAC_API" + doErr.Error())

    }


    //Check if the request was successful

    if resp.StatusCode != 200 {

        return fmt.Errorf("COULD_NOT_CHANGE_SERVER_POWER_STATUS_OVER_IDRAC HTTP:" + resp.Status)

    }


    return nil

}

我用来构建请求的辅助函数:


func (iDrac *IDrac) buildHttpRequestWithAuthorizationHeader(method string, url string, content string) (*http.Request, error) {


    req, err := http.NewRequest(method, url, bytes.NewBuffer([]byte(content)))

    if err != nil {

        return nil, err

    }


    req.Header.Add("Authorization", "Basic "+iDrac.hashedCredentials)

    return req, nil

}

最后是模型处理请求的函数:


func handlePerformReset(w http.ResponseWriter, r *http.Request) {

    garbagelog.Log("Handling reset perform request from " + r.RemoteAddr)


    if r.Method != http.MethodPost {

        garbagelog.Log("Invalid http method! Got " + r.Method + " expected POST")

        w.WriteHeader(405)

        return

    }

    if !checkAuthorization(r.BasicAuth()) {

        w.WriteHeader(401)

        return

    }