du1462 2019-03-05 16:51
浏览 159

在Golang中管理多种返回类型

I'm a bit new to Go and I'm having trouble converting a response object from an API call into different structures based on the request type

Essentially, I have one func which sends out a request

func (fpc *FPClient) request(path string, method string, params interface{}, Token string, response interface{}) *dto.AppError {
    client := &http.Client{
        Timeout: time.Second * 15,
    }
    requestBody, err := json.Marshal(params)
    if err != nil {
         //
    }

    req, _ := http.NewRequest(method, path, bytes.NewBuffer(requestBody))
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("Cookie", fmt.Sprintf("cookie=%s;", Token))
    req.SetBasicAuth(fpc.username, fpc.password)
    resp, err := client.Do(req)

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

    if err != nil {
       //
    }
    if FPErr := fpc.processErrors(resp, body); FPerr != nil {
        return FPErr
    }

    responseData := FPApiSuccess{Head: response, Body: response}
    if err := json.Unmarshal(body, &responseData); err != nil {
       //
    }
    fmt.Printf("

 client Response : 
 %+v 
", responseData.Body)
    return nil
}

The struct for FPApiSuccess is:

type FPApiSuccess struct {
    Body interface{} `json:"body"`
    Head interface{} `json:"head"`
}

Right now, there are 2 calling functions and the API response expected is a bit different for both

Both API responses have the below structure

{
    "head": {},
    "body": {}
}

However, the nested details in each key is different based on the API used.

I want to capture the head and body keys in a struct argument I give and send it back to the calling function. The response argument in the request function is a different struct type based on the calling function.

I'm unable to get this to work - I'm only getting back a blank struct from the request function. This is the fmt.PrintF log

 client Response : 
 &{Body:{BOrderID:0 CC: Exch: EOID: Type: Local:0 Message: } Head:{ResponseCode: Status: StatusDescription:}} 

This is an empty struct - ideally, it should be populated with the values retrieved from the API.

For reference, heres the struct passed as an argument as response in the request function:

   type FPApiResponse struct {
        Body FPBodyResponse `json:"body"`
        Head FPHeadResponse `json:"head"`
    }

    type FPHeadResponse struct {
        ResponseCode      string `json:"responseCode"`
        Status            string `json:"status"`
        StatusDescription string `json:"statusDescription"`
    }

    type FPBodyResponse struct {
        BOrderID   int    `json:"BOrderID"`
        CC      string `json:"CC"`
        Exch            string `json:"Exch"`
        EOID     string `json:"EOID"`
        Type        string `json:"Type"`
        Local    int    `json:"Local"`
        Message         string `json:"Message"`
    }

Update

So I did this; instead of

responseData := FPApiSuccess{Head: response, Body: response}

I did this

responseData := fivePaisaApiSuccess{}

So now, I get the below in console

 Client Response : 
 {Body:map[BOrderID:0 CC:52715111 Type:D Local:0 Message:Invalid Session ] Head:map[responseCode:5POrdReq status:0 statusDescription:Success]} 

So essentially, this works, but the calling function doesn't seem to get the proper response:

Here's the calling function

func (fpc *FPClient) PlaceOrder(orderParams dto.OrderBodyParams, variety string, Token string) (string, *dto.AppError) {
    var result FPApiResponse

    headParams := dto.FFPOrderHeadParams{
      //
    }
    FPOrderParams := dto.FPOrderParams{
       //
    }
    FPErr := fpc.request(FPURL+FPPlaceOrder, http.MethodPost, FPOrderParams, brokerAccessToken, &result)
    if FPErr != nil {
        return "", FPErr
    }
    fmt.Printf("

 Client result : 
 %+v 
", result)
    if result.Head.Status != "0" {
       //
    }

    if result.Body.Status != 0 {
      //
    }
    return strconv.Itoa(result.Body.Broker), nil
}

The result value is blank:

 {Body:{BOId:0 CC: Exch: Type: Local:0 Message: Status:0} Head:{ResponseCode: Status: StatusDescription:}}

I don't understand, this pointer is getting populated in the request function

Here's the struct I'm passing to the request:

type FPApiResponse struct {
    Body FPBodyResponse `json:"body"`
    Head FPHeadResponse `json:"head"`
}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 下图接收小电路,谁知道原理
    • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
    • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
    • ¥15 手机接入宽带网线,如何释放宽带全部速度
    • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
    • ¥15 ETLCloud 处理json多层级问题
    • ¥15 matlab中使用gurobi时报错
    • ¥15 这个主板怎么能扩出一两个sata口
    • ¥15 不是,这到底错哪儿了😭
    • ¥15 2020长安杯与连接网探