附加到结构片

时间:2018-11-19 10:03:28

标签: go

我在初始化结构片段并将其添加到其中时遇到问题。

我试图为下面的JSON建模,所以我为单个错误创建了一个名为Error的结构,并创建了一部分Errors来保存它们。我知道我可以做errSlice := []Err{},但不会显示JSON标签。

{
  "errors": [
    {
      "status": "422",
      "source": { "pointer": "/data/attributes/firstName" },
      "title":  "Invalid Attribute",
      "detail": "First name must contain at least three characters."
    }
  ]
}

我的尝试

package main

import (
    "encoding/json"
    "net/http"
)

// ErrSlice is a slice of type Err
type ErrSlice struct {
    Errors []Err `json:"errors"`
}

// Err is an error
type Err struct {
    Status string `json:"status"`
    Source Source `json:"source"`
    Title  string `json:"title"`
    Detail string `json:"detail"`
}

// Source is struct of error source
type Source struct {
    Pointer string `json:"pointer"`
}

func main() {
    http.HandleFunc("/", foo)
    http.ListenAndServe(":9001", nil)
}

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

    errSlice := ErrSlice{}

    // New error
    err1 := Err{
        Status: "422",
        Source: Source{
            Pointer: "/data/attributes/firstName",
        },
        Title:  "Invalid Attribute",
        Detail: "First name must contain at least three characters.",
    }

    // Append err1 to errSlice
    errSlice = append(errSlice, err1) // error: "first argument to append must be slice"

    // Marshall errSlice
    jsonErrSlice, _ := json.Marshal(errSlice)

    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusUnprocessableEntity)
    w.Write(jsonErrSlice)
}

感谢您的时间!

1 个答案:

答案 0 :(得分:0)

我想出了一种获取所需格式的方法,但是我敢肯定有一种更干净的方法来实现此目的:

package main

import (
    "encoding/json"
    "net/http"
)

// Err struct are individual errors
type Err struct {
    Status string `json:"status"`
    Source Source `json:"source"`
    Title  string `json:"title"`
    Detail string `json:"detail"`
}

// Source is a struct for source inside an error
type Source struct {
    Pointer string `json:"pointer"`
}

// JSONErrors stores the json error data
type JSONErrors struct {
    Errors []Err `json:"errors"`
}

func main() {
    http.HandleFunc("/", foo)
    http.ListenAndServe(":9001", nil)
}

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

    // Create slice of errors
    errSlice := []Err{}

    // New error
    err1 := Err{
        Status: "422",
        Source: Source{
            Pointer: "/data/attributes/firstName",
        },
        Title:  "Invalid Attribute",
        Detail: "First name must contain at least three characters.",
    }

    // Append to error slice
    errSlice = append(errSlice, err1)

    // Assign errSlice to JSONErrors
    jsonErrRes := JSONErrors{Errors: errSlice}

    // Marshall errSlice
    jsonErrSlice, _ := json.Marshal(jsonErrRes)

    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusUnprocessableEntity)
    w.Write(jsonErrSlice)

    // Results:
    // {
    //  "errors": [
    //      {
    //          "status": "422",
    //          "source": {
    //              "pointer": "/data/attributes/firstName"
    //          },
    //          "title": "Invalid Attribute",
    //          "detail": "First name must contain at least three characters."
    //      }
    //  ]
    // }
}