douxian6086 2014-06-11 09:08
浏览 64
已采纳

我被困在json.marshal中

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
", *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条回答 默认 最新

  • dsd30433 2014-06-11 09:11
    关注

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建