登录
首页 >  Golang >  Go问答

添加 go-swagger 引用数组和地图模型的示例

来源:stackoverflow

时间:2024-04-03 14:51:33 355浏览 收藏

从现在开始,我们要努力学习啦!今天我给大家带来《添加 go-swagger 引用数组和地图模型的示例》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎留言呀!我们一起讨论,一起学习!

问题内容

我正在尝试使用 go-swagger 生成我的服务 swagger 规范

我有一个类似的响应结构

type MyResponse struct {
    // example: ["This", "Is", "A", "Test"] 
    MyTestArray   MyArray `json:"MyTestArray"`
}

type MyArray []string

所以,myarray 只是 []string 的 typedef,但是当我尝试使用 // example: 字段时,它不起作用,因为 myarray 是一个引用模型。当我直接在结构中使用 []string 时,它可以工作。有没有办法使用 go-swagger 添加引用数组模型的示例?


正确答案


这个问题与 go-swagger 无关,您只需将数组键入并格式化为 json 即可与 go-swagger 兼容。一种方法是为 myarray (及其架构 - myarrayschema)创建单独的模型定义,然后在 myresponse 结构(及其架构 - myresponseschema)中引用它。像这样(在 Playground 中运行):

// so testing by js

package main

import (
    "encoding/json"
    "fmt"
)

type myarray struct {
    items []string `json:"items"`
}

type myarrayschema struct { // defining a schema for myarray + example

    type    string   `json:"type"`
    items   []string `json:"items"`
    example []string `json:"example"`
}

type myresponse struct {
    mytestarray myarray `json:"mytestarray"`
}

type myresponseschema struct { // define a schema for myresponse + example

    type       string `json:"type"`
    properties struct {
        mytestarray myarrayschema `json:"mytestarray"`
    } `json:"properties"`
    example struct {
        mytestarray []string `json:"mytestarray"`
    } `json:"example"`
}

func main() {
    // fmt.println("hello, namaste!")

    myarray := myarray{
        items: []string{"is", "this", "a", "test", "or", "am", "i", "serialized", "?"},
    }

    myresponse := myresponse{
        mytestarray: myarray,
    }

    myresponsejson, err := json.marshal(myresponse)
    if err != nil {
        fmt.println("error marshaling myresponse to json:", err)
        return
    }

    fmt.println(string(myresponsejson))
}

演示代码的输出:

{"MyTestArray":{"items":["Is","This","A","Test","Or","Am","I","Serialized","?"]}}

Program exited.

到这里,我们也就讲完了《添加 go-swagger 引用数组和地图模型的示例》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>