2014-06-11 12 views
12

Sono newbie completo in go, iniziato pochi giorni fa. Voglio collegarmi a mongodb, cercare, creare un servizio e usarlo per l'angolare. Ho fatto quasi tutto ma ho problemi con json.marshal(). Qualcuno può dirmi cosa sto sbagliando, o c'è un modo migliore? thx :)Sono bloccato con json.marshal in go

L'errore è "./main.go:96: multiple-value json.Marshal() in un contesto unico valore"

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 
} 

risposta

34

Guardate la documentazione di questa funzione: http://golang.org/pkg/encoding/json/#Marshal

func Marshal(v interface{}) ([]byte, error) 

Restituisce due valori. Il problema qui è che basta dargli una variabile per ottenere questi due valori:

b := json.Marshal(result) 

Quindi, non resta che correggere in questo modo:

b, err := json.Marshal(result) 
+1

SI, thx uomo che mi ha salvato un altro paio di ore : DI accetterà la tua risposta in pochi minuti – Arcagully