API请求和响应

时间:2019-04-01 11:58:13

标签: json go

我想找出HTTP客户端是否可以在Go中使用其他JSON对象发布特定的JSON对象和服务器响应。例如,客户端发送JSON对象

请求正文

{
  "nfNssaiAvailabilityUri": "string",
  "taiList": [
    {
      "plmnId": {
        "mcc": "string",
        "mnc": "string"
      },
      "tac": "string"
    }
  ],
  "expiry": "2019-04-01T10:41:54.344Z"
}

响应正文为

{
  "subscriptionId": "string",
  "expiry": "2019-04-01T10:41:54.363Z",
  "authorizedNssaiAvailabilityData": [
    {
      "tai": {
        "plmnId": {
          "mcc": "string",
          "mnc": "string"
        },
        "tac": "string"
      },
      "supportedSnssaiList": [
        {
          "sst": 0,
          "sd": "string"
        }
      ],
      "restrictedSnssaiList": [
        {
          "homePlmnId": {
            "mcc": "string",
            "mnc": "string"
          },
          "sNssaiList": [
            {
              "sst": 0,
              "sd": "string"
            }
          ]
        }
      ]
    }
  ]
}

如您所见,请求正文JSON与响应不同。我有两个JSON的结构,目前我只能使用请求正文进行POST,并且接收与响应相同的正文。期望能够获得上述响应中指示的JSON对象。

我有:

type NssfEventSubscriptionCreateData struct {
    NfNssaiAvailabilityUri string `json:"nfNssaiAvailabilityUri"`
    TaiList []Tai `json:"taiList,omitempty"`
        ...
}
type NssfEventSubscriptionCreatedData struct {
    SubscriptionId string `json:"subscriptionId"`
    Expiry time.Time `json:"expiry,omitempty"`
        ....
}
func (m *SliceDataAccess) InsertNssaiSubscriptionInfo(subdata NssfEventSubscriptionCreateData) error {
    err := db.C(COLLECTION).Insert(subdata)
    if err != nil {
        return err
    }
    return nil
}
func NSSAIAvailabilityPost(w http.ResponseWriter, r *http.Request) {
    if r.Header.Get("Accept") != "application/json" {
        WriteError(w, ErrNotAcceptable)
        return
    }
    if r.Method == "POST" {

        var reqsubData NssfEventSubscriptionCreateData
        err := json.NewDecoder(r.Body).Decode(&reqsubData)
        if err != nil {
            respondWithError(w, http.StatusBadRequest, "Object body not well decoded")
            return
        }
        //reqsubData.ID = bson.NewObjectId()
        if err := da.InsertNssaiSubscriptionInfo(reqsubData); err != nil {
            respondWithError(w, http.StatusInternalServerError, err.Error())
        } else {
            scheme := "http"
            if r.URL.Scheme != "" {
                scheme = r.URL.Scheme
            }
            w.Header().Set("Location", scheme+"://"+r.Host+r.URL.Path)
            w.Header().Set("Response-Code", "201")
            w.Header().Set("Response-Desc", "Success")
            respondWithJson(w, http.StatusCreated, reqsubData)
        }

    }
}

NSSAIAvailabilityPost函数使用NssfEventSubscriptionCreateData结构类型JSON对象进行响应,但是我希望能够使用NssfEventSubscriptionCreatedData结构类型JSON对象进行响应。

1 个答案:

答案 0 :(得分:0)

创建类型为NssfEventSubscriptionCreatedData的结构,以初始化其值并返回responseWithJSON。

respData : = NssfEventSubscriptionCreatedData{}
// init fields

 respondWithJson(w, http.StatusCreated, respData)