dragon2025 2019-03-10 22:05
浏览 89
已采纳

如何通过JSON将所有记录正确显示为数组

For past 38 hours now I have been learning golang and coding this. This is what this code does.

The golang code below display two post records from database in an array via json. At the moment this is the json response am getting when I run the code and is okay for now..

[
{"id":"1",
"title":"Post Title 1 ",
"content":"post content 1."
},

{"id":"2",
"title":"post Title 2 ",
"content":"post content 2 "
}
]

At the moment, postlikeCount and postunlikeCount are not fetched in the array because they reside in another table.

If everything works fine, am supposed to get an array like this which contains everything like the sample below.

[
{"id":"1",
"title":"Post Title 1 ",
"content":"post content 1.",
"postlikeCount":"2",
"postunlikeCount":"1"},

{"id":"2",
"title":"post Title 2 ",
"content":"post content 2 ",
"postlikeCount":"4",
"postunlikeCount":"0"}
]

Now to get postlikeCount and postunlikeCount, I have implemented two sect of codings below which I passed within post for rows.next() functions.

// get postlikeCount based on userid and postid
var userid =5
var  postlikeCount int
err := db.QueryRow("SELECT COUNT(*) as postlikeCount FROM postData WHERE postid=? and userid=?", postid,userid).Scan(&postlikeCount)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Number of postlikeCount rows are %s
",  postlikeCount)


// get postunlikeCount  based on userid and postid

var  postunlikeCount int
err1 := db.QueryRow("SELECT COUNT(*) as postunlikeCount FROM postData WHERE postid=? and userid=?", postid,userid).Scan(&postunlikeCount)
if err1 != nil {
    log.Fatal(err1)
}

fmt.Printf("Number of postunlikeCount rows are %s
",  postunlikeCount)

The above two code works fine as I can Print their respective post like and unlike counts.

Here is my Issue:

When I tried to pass and append the postlikeCount and postunlikeCount parameters so that I can print them in json as per this line of code

posts = append(posts, post, postlikeCount,postunlikeCount)

It displays error

cannot postlikeCount (type int) as type post in append
cannot use postunlikeCount (type int) as type post in append

Does this error has to do with Struct function. Please can someone help me fix this. I need to pass postlikeCount and postunlikeCount as part of json as can be seen the complete array result above.

here is the full working code so far.

package main

import "database/sql"
import _ "github.com/go-sql-driver/mysql"

import "net/http"
import "fmt"
import "encoding/json"
import "log"

var db *sql.DB
var err error

type Post struct {
Id  int
Title string
Content string  

}



func getRecordPage1(res http.ResponseWriter, req *http.Request) {

    if req.Method != "POST" {
        http.ServeFile(res, req, "getjsonRecord.html")
        return
    }


var (
post  Post
posts []Post
)

rows, err := db.Query("SELECT id,title,content FROM posts")
if err != nil {
            http.Error(res, "display error, unable to select records in json", 500)
            return
        }

for rows.Next() {

var postid =post.Id
var title = post.Title
var content = post.Content

fmt.Printf("%s is now %d
", postid, title, content)


// get postlikeCount based on userid and postid
var userid =5
var  postlikeCount int
err := db.QueryRow("SELECT COUNT(*) as postlikeCount FROM postData WHERE postid=? and userid=?", postid,userid).Scan(&postlikeCount)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Number of postlikeCount rows are %s
",  postlikeCount)


// get postunlikeCount  based on userid and postid

var  postunlikeCount int
err1 := db.QueryRow("SELECT COUNT(*) as postunlikeCount FROM postData WHERE postid=? and userid=?", postid,userid).Scan(&postunlikeCount)
if err1 != nil {
    log.Fatal(err1)
}

fmt.Printf("Number of postunlikeCount rows are %s
",  postunlikeCount)





rows.Scan(&post.Id, &post.Title, &post.Content)
posts = append(posts, post)

//like of code comment which causes issues
//posts = append(posts, post,postlikeCount,postunlikeCount)
}
defer rows.Close()


jsonResponse, jsonError := json.Marshal(posts)
if jsonError != nil {
fmt.Println(jsonError)
}

if jsonResponse == nil {
fmt.Println(jsonError)
} else {
res.Header().Set("Content-Type", "application/json")
res.Write(jsonResponse)
 fmt.Println("Json results displayed successfully")
}



}



func homePage(res http.ResponseWriter, req *http.Request) {
    http.ServeFile(res, req, "index.html")
}

func main() {
    db, err = sql.Open("mysql", "root:@/golang44")
    if err != nil {
        panic(err.Error())
    }
    defer db.Close()

    err = db.Ping()
    if err != nil {
        panic(err.Error())
    }

    http.HandleFunc("/getjsonRecord", getRecordPage1)
    http.HandleFunc("/", homePage)
        fmt.Println("Listening on 127.0.0.1:8088")
    http.ListenAndServe(":8088", nil)
}
  • 写回答

1条回答 默认 最新

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥20 从零开始汽车自动驾驶相关的软件学习
      • ¥30 操作系统进程实验虚拟机
      • ¥15 yolov5摄像头识别只能检测第一帧图像
      • ¥15 有没有可以下载钉钉群文件视频的软件
      • ¥15 如何用LaTeX打出如下的表格
      • ¥15 程序填空补充完整的代码一共三题
      • ¥15 在MySQL中使用while建表,报错
      • ¥15 python导入pyautogui报错,网上也没有找到解决方法如何解决?
      • ¥15 关于IPSEC和NAT SERVER同时使用的情况下,该如何解决客户端访问服务器的问题
      • ¥15 eclipse项目在idea运行部署到云服务器