Golang - 如何使单个结构与多个结构一起工作?

时间:2015-06-07 11:28:45

标签: go

我想让单个结构与多个结构一起工作。

在下面的代码中,第一个查询(rows)应该是单个结构,因为它返回单行,而第二个查询(anotherquery)应该是多个结构,因为它返回5行。

目前,我可以做的是rows& anotherquery为多个结构。

以下是server.go

package main

import (
    "database/sql"
    "github.com/labstack/echo"
    _ "github.com/lib/pq"
    "html/template"
    "io"
    "log"
    "net/http"
)

type Gallery struct {
    Title, Content string
}
type Idcontainer struct {
    Stitle, Suri string
}

func main() {
    e := echo.New()

    e.Get("/post/:uritext", func(c *echo.Context) error {

        rows, err := db.Query("SELECT title, content FROM gallery WHERE uri=$1", c.Param("uritext"))
        anotherquery, err := db.Query("SELECT title AS stitle, uri AS suri FROM archive WHERE uri!=$1 LIMIT 5", c.Param("uritext"))

        gallery := []Gallery{}
        idcontainer := []Idcontainer{}

        for rows.Next() {
            g := Gallery{}
            err := rows.Scan(&g.Title, &g.Content)

            gallery = append(gallery, g)
        }

        for anotherquery.Next() {
            g := Idcontainer{}
            err := anotherquery.Scan(&g.Stitle, &g.Suri)

            idcontainer = append(idcontainer, g)
        }

        type Model struct {
            Galleries    []Gallery
            Idcontainers []Idcontainer
        }
        return c.Render(http.StatusOK, "onlytestingtpl", Model{
            Galleries:    gallery,
            Idcontainers: idcontainer,
        })
    })

    e.Run(":4444")
}

模板:

{{define "onlytestingtpl"}}
    {{.Title}}<br>
    {{.Content}}

    <h1>ID number:</h1>
    {{range .Idcontainers}}
    <a href='{{.Suri}}'>{{.Stitle}}</a>
    {{end}}
{{end}}

1 个答案:

答案 0 :(得分:1)

我认为对您的代码进行最小程度的更改将是以下内容。

改变这个:

    type Model struct {
        Galleries    []Gallery
        Idcontainers []Idcontainer
    }
    return c.Render(http.StatusOK, "onlytestingtpl", Model{
        Galleries:    gallery,
        Idcontainers: idcontainer,
    })

对此:

    type Model struct {
        Gallery    Gallery // you said that theres only a single gallery right?
        Idcontainers []Idcontainer
    }
    return c.Render(http.StatusOK, "onlytestingtpl", Model{
        Gallery:    gallery[0],
        Idcontainers: idcontainer,
    })

然后将模板更改为:

{{define "onlytestingtpl"}}
    {{.Gallery.Title}}<br>
    {{.Gallery.Content}}

    <h1>ID number:</h1>
    {{range .Idcontainers}}
    <a href='{{.Suri}}'>{{.Stitle}}</a>
    {{end}}
{{end}}

我试图在这里模拟一个简单的例子:http://play.golang.org/p/uedcjXalEH

虽然你没有要求对整体代码提出反馈意见,但我还是冒险添加一些额外的评论:

  • 考虑对对象使用*(指针)而不是每次都复制。
  • 考虑将您的初始rows更改为以下内容:

    gallery := Gallery{}
    if !rows.Next() {
        return rows.Err()
    }
    err := rows.Scan(&gallery.Title, &gallery.Content)
    
    // anotherquery remains the same ...
    
    return c.Render(http.StatusOK, "onlytestingtpl", Model{
        Gallery:    gallery,
        Idcontainers: idcontainer,
    })
    
  • 这可能只是示例代码,但在生产中,当然需要更多错误处理:)

希望这有帮助。