英文:
I'm stuck with json.marshal in go
问题
我是一个中文翻译助手,以下是你提供的代码的翻译:
我是一个刚刚开始学习Go语言的新手,几天前开始学习。我想连接到MongoDB,进行搜索,创建一个服务,并在Angular中使用它。我几乎完成了所有的工作,但是在json.marshal()这一步遇到了问题。有人可以告诉我我做错了什么,或者有更好的方法吗?谢谢 :)
错误信息是:
"./main.go:96: 在单值上下文中使用了多值json.Marshal()"
package main
import (
"encoding/json"
"flag"
"fmt"
"github.com/gorilla/mux"
"labix.org/v2/mgo"
"labix.org/v2/mgo/bson"
"log"
"net/http"
)
type warrior struct {
Name string `json:"name"`
LowDamage int `json:"low_damage"`
HighDamage int `json:"high_damage"`
Health int `json:"health"`
HealthLeft int `json:"health_left"`
Armor int `json:"armor"`
Id bson.ObjectId `json:"_id,omitempty"`
}
func getWarriors(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
w.Write(mongo())
}
func main() {
// 命令行标志
port := flag.Int("port", 5001, "要监听的端口")
dir := flag.String("random message 1", "web/", "random message 2")
flag.Parse()
// 通过提供相同名称的文件来处理所有请求
fs := http.Dir(*dir)
fileHandler := http.FileServer(fs)
// 路由
router := mux.NewRouter()
router.Handle("/", http.RedirectHandler("/static/", 302))
router.HandleFunc("/warriors", getWarriors).Methods("GET")
router.PathPrefix("/static/").Handler(http.StripPrefix("/static", fileHandler))
http.Handle("/", router)
log.Printf("运行在端口 %d\n", *port)
addr := fmt.Sprintf("127.0.0.1:%d", *port)
err := http.ListenAndServe(addr, nil)
fmt.Println(err.Error())
}
func mongo() []byte {
session, err := mgo.Dial("mongodb://localhost:27017/test")
if err != nil {
panic(err)
}
defer session.Close()
// 可选的。将会话切换为单调模式。
session.SetMode(mgo.Monotonic, true)
// 选择数据库和表名
c := session.DB("test").C("warriors")
e := warrior{
Name: "first event",
LowDamage: 2,
HighDamage: 4,
Health: 40,
HealthLeft: 40,
Armor: 1,
}
// 插入数据
err = c.Insert(e)
if err != nil {
panic(err)
}
// 搜索并显示结果 []warrior{} for all warrior{}
result := []warrior{}
// err = c.Find(bson.M{"name": "first event"}).One(&result)
err = c.Find(bson.M{"name": "first event"}).Limit(10).All(&result)
if err != nil {
panic(err)
}
b, err := json.Marshal(result)
if err != nil {
panic(err)
}
log.Println("JSON:", result)
return b
}
希望对你有帮助!如果你有任何其他问题,请随时问我。
英文:
I'm complete newbie in go, started few days ago. I want to connect to mongodb, search, create a service and use it for angular. I've done almost everything but I have problem with json.marshal(). Can someone tell me what am I doing wrong, or is there a better way? thx
The error is
"./main.go:96: multiple-value json.Marshal() in single-value context"
package main
import (
"encoding/json"
"flag"
"fmt"
"github.com/gorilla/mux"
"labix.org/v2/mgo"
"labix.org/v2/mgo/bson"
"log"
"net/http"
)
type warrior struct {
Name string `json:"name"`
LowDamage int `json:"low_damage"`
HighDamage int `json:"high_damage"`
Health int `json:"health"`
HealthLeft int `json:"health_left"`
Armor int `json:"armor"`
Id bson.ObjectId "_id,omitempty"
}
func getWarriors(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
w.Write(mongo())
}
func main() {
// command line flags
port := flag.Int("port", 5001, "port to serve on")
dir := flag.String("random message 1", "web/", "random message 2")
flag.Parse()
// handle all requests by serving a file of the same name
fs := http.Dir(*dir)
fileHandler := http.FileServer(fs)
// ROUTES
router := mux.NewRouter()
router.Handle("/", http.RedirectHandler("/static/", 302))
router.HandleFunc("/warriors", getWarriors).Methods("GET")
router.PathPrefix("/static/").Handler(http.StripPrefix("/static", fileHandler))
http.Handle("/", router)
log.Printf("Running on port %d\n", *port)
addr := fmt.Sprintf("127.0.0.1:%d", *port)
err := http.ListenAndServe(addr, nil)
fmt.Println(err.Error())
}
func mongo() []byte {
session, err := mgo.Dial("mongodb://localhost:27017/test")
if err != nil {
panic(err)
}
defer session.Close()
// Optional. Switch the session to a monotonic behavior.
session.SetMode(mgo.Monotonic, true)
// select dm + table name
c := session.DB("test").C("warriors")
e := warrior{
Name: "first event",
LowDamage: 2,
HighDamage: 4,
Health: 40,
HealthLeft: 40,
Armor: 1,
}
// insert data
err = c.Insert(e)
if err != nil {
panic(err)
}
// search show results []warrior{} for all warrior{}
result := []warrior{}
// err = c.Find(bson.M{"name": "first event"}).One(&result)
err = c.Find(bson.M{"name": "first event"}).Limit(10).All(&result)
if err != nil {
panic(err)
}
b := json.Marshal(result)
log.Println("JSON:", result)
return b
}
答案1
得分: 35
请查看此函数的文档:http://golang.org/pkg/encoding/json/#Marshal
func Marshal(v interface{}) ([]byte, error)
它返回两个值。问题在于你只给了一个变量来接收这两个值:
b := json.Marshal(result)
所以你只需要按照以下方式进行更正:
b, err := json.Marshal(result)
英文:
Look at the documentation of this function: http://golang.org/pkg/encoding/json/#Marshal
func Marshal(v interface{}) ([]byte, error)
It returns two values. The problem here is that you just give it one variable to get those two values:
b := json.Marshal(result)
So you just have to correct it this way:
b, err := json.Marshal(result)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论