简体   繁体   English

不允许嵌套函数

[英]Go nested func not allowed

I want to get the values of one table of my db and parse them in an html. 我想获取数据库的一个表的值并将其解析为html。 This is the code that I used to try to do it but I got an error called nested func not allowed . 这是我用来尝试执行的代码,但是出现了一个错误消息,称为nested func not allowed

I started creating an estructure: 我开始创建一个estructure:

type App struct{
    Title string
    Author string
    Description string
}

I created a function to render the templates: 我创建了一个渲染模板的函数:

func render(w http.ResponseWriter, tmpl string){
    tmpl = fmt.Sprintf("templates/%s", tmpl)
    t, err := template.ParseFiles(tmpl)
    if err != nil{
        log.Print("template parsing error: ", err)
    }
    err = t.Execute(w, "")
    if err != nil{
        log.Print("template executing error: ", err)
    }
}

Then, here I got the apps from the database and try to render them to the html. 然后,在这里,我从数据库中获取了应用程序,并尝试将它们呈现为html。

func myApps(w http.ResponseWriter, r *http.Request){
    db, err := sql.Open("postgres"," user=postgres dbname=test host=localhost password=1234 sslmode=disable")
    if err != nil{
        log.Fatal(err)
    }
        rows, err := db.Query(`SELECT title, author, description FROM apps
                                 WHERE title ILIKE $1
                                 OR author ILIKE $1
                                 OR description ILIKE $1`)
            defer rows.Close()

            apps := []App{}
            for rows.Next(){
                b := App{}
                err := rows.Scan(&b.Title, &b.Author, &b.Description)
                apps = append(apps, b)

    render(w, "myapps.html", apps)
}

Thank you in Advance! 先感谢您!

There might be some type around the line including a for statement : 可能会有一些类型,包括for语句

for rows.Next(){

I don't see that opening ' { ' closed anywhere else. 我看不到其他任何地方都没有打开' { '。

(Or it is closed, but then func myApps isn't closed) (或者它是关闭的,但是func myApps没有关闭)

Maybe it should be: 也许应该是:

        for rows.Next() {
            b := App{}
            err := rows.Scan(&b.Title, &b.Author, &b.Description)
            apps = append(apps, b)
        }
        render(w, "myapps.html", apps)
}

In any case, running go fmt is always a good idea. 无论如何,运行go fmt总是一个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM