英文:
Create json fro Cassandra in go
问题
我有一个在Cassandra中定义的表,如下所示:
CREATE TABLE book.book
(
title text PRIMARY KEY,
amount decimal,
available int,
createdon timestamp
)
我想从该表中选择所有数据,并以JSON格式返回这些值。我可以通过以下方式实现:
type Book struct {
Title string json:"title"
Amount inf.Dec json:"amount"
CreatedOn time.Time json:"createdon"
Available int json:"available"
}
使用以下代码:
func cassandraDisplay(query string, w http.ResponseWriter) {
cluster := gocql.NewCluster("xxxxxxxx:xxxx")
session, _ := cluster.CreateSession()
defer session.Close()
iter := session.Query("SELECT * FROM book.book").Iter()
var book Book
for iter.Scan(&book.Title, &book.Amount, &book.CreatedOn, &book.Available) {
fmt.Println(book.Title, book.Amount, book.CreatedOn, book.Available)
j, err := json.Marshal(&book)
if err != nil {
panic(err)
}
// 对 j 进行处理
}
if err := iter.Close(); err != nil {
log.Fatal(err)
}
}
但要求是动态的,不能硬编码任何信息;由于它是一个HTTP服务,查询将通过URL传递。有什么办法可以实现这个要求吗?
英文:
I have a table in Cassandra defined as the following :
CREATE TABLE book.book
(
title text PRIMARY KEY,
amount decimal,
available int,
createdon timestamp
)
I am trying to select * from that table and return the values in json format. I am able to achieve that using
type Book struct {
Title string `json:"title"`
Amount inf.Dec `json:"amount"`
CreatedOn time.Time `json:"createdon"`
Available int `json:"available"`
}
with
func cassandraDisplay(query string, w http.ResponseWriter) {
cluster := gocql.NewCluster("xxxxxxxx:xxxx")
session, _ := cluster.CreateSession()
defer session.Close()
iter := session.Query("SELECT * FROM book.book").Iter()
var book Book
for iter.Scan(&book.Title ,&book.Amount ,&book.CreatedOn,&book.Available{
fmt.Println(book.Title , book.Amount,book.CreatedO,book.Available)
j, ERR:= json.Marshal(&iter)
if ERR != nil {panic(ERR)}
//do things with j
}
if err := iter.Close(); err != nil {log.Fatal(err)}
}
but the requirement require a dynamic and no hard coding any info; since it is http service and the query will be passed through the url.
Any idea how to get this to work?
答案1
得分: 1
@Michael,
你可能想使用MapScan:https://godoc.org/github.com/gocql/gocql#Iter.MapScan
这是最抽象的方法。
从https://github.com/gocql/gocql/blob/master/cassandra_test.go中可以看到:
...
testMap := make(map[string]interface{})
if !session.Query(`SELECT * FROM slice_map_table`).Iter().MapScan(testMap) {
t.Fatal("MapScan failed to work with one row")
}
...
之后你需要反射/探索map的内容,但这是另一个话题。
英文:
@Michael,
You may want to use MapScan: https://godoc.org/github.com/gocql/gocql#Iter.MapScan
This is as abstract as it can get.
From https://github.com/gocql/gocql/blob/master/cassandra_test.go:
...
testMap := make(map[string]interface{})
if !session.Query(`SELECT * FROM slice_map_table`).Iter().MapScan(testMap) {
t.Fatal("MapScan failed to work with one row")
}
...
And after that you'll need to reflect/explore map content, but that's a different topic.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论