json - 这里为什么要用到json包的Decode和Marshal方法呢?

标签 json go

在以下示例中来自 Web Development with Go by Shiju Varghese ,用于为每个 HTTP 请求使用新的 MongoDB session 来实现 HTTP 服务器:

  • PostCategory函数为什么使用json包的Decode方法?

  • 为什么在GetCategories函数中使用了json包的Marshal方法?

一开始以为PostCategory中的DecodeGetCategories中的Marshal是相反的,但是后来我发现在json包中有一个Unmarshal方法,也许还有一个Encode方法。所以我问了a question早些。

这是程序

package main
import (
    "encoding/json"
    "log"
    "net/http"
    "github.com/gorilla/mux"
    "gopkg.in/mgo.v2"
    "gopkg.in/mgo.v2/bson"
)
var session *mgo.Session

type (
    Category struct {
Id bson.ObjectId `bson:"_id,omitempty"`
Name string
Description string
    }
    DataStore struct {
session *mgo.Session
    }
)
//Close mgo.Session
func (d *DataStore) Close() {
    d.session.Close()
}
//Returns a collection from the database.
func (d *DataStore) C(name string) *mgo.Collection {
    return d.session.DB("taskdb").C(name)
}
//Create a new DataStore object for each HTTP request
func NewDataStore() *DataStore {
    ds := &DataStore{
session: session.Copy(),
    }
    return ds
}

//Insert a record
func PostCategory(w http.ResponseWriter, r *http.Request) {
    var category Category
    // Decode the incoming Category json
    err := json.NewDecoder(r.Body).Decode(&category)
    if err != nil {
panic(err)
    }
    ds := NewDataStore()
    defer ds.Close()
    //Getting the mgo.Collection
    c := ds.C("categories")
    //Insert record
    err = c.Insert(&category)
    if err != nil {
panic(err)
    }
w.WriteHeader(http.StatusCreated)
}

//Read all records
func GetCategories(w http.ResponseWriter, r *http.Request) {
    var categories []Category
    ds := NewDataStore()
    defer ds.Close()
    //Getting the mgo.Collection
    c := ds.C("categories")
    iter := c.Find(nil).Iter()
    result := Category{}
    for iter.Next(&result) {
categories = append(categories, result)
    }
w.Header().Set("Content-Type", "application/json")
j, err := json.Marshal(categories)
if err != nil {
panic(err)
    }
w.WriteHeader(http.StatusOK)
w.Write(j)
}

func main() {
    var err error
    session, err = mgo.Dial("localhost")
    if err != nil {
panic(err)
    }
    r := mux.NewRouter()
r.HandleFunc("/api/categories", GetCategories).Methods("GET")
r.HandleFunc("/api/categories", PostCategory).Methods("POST")
    server := &http.Server{
Addr:    ":8080",
Handler: r,
    }
    log.Println("Listening...")
    server.ListenAndServe()
}

最佳答案

我认为这里使用 json.NewDecoder 的主要原因是直接从这里的响应主体 (r.Body) 读取,因为 NewDecoderio.Reader 作为输入。

您可以使用 json.Unmarshal,但您必须先将响应主体读入 []byte 并将该值传递给 json。解码NewDecoder 在这里更方便。

关于json - 这里为什么要用到json包的Decode和Marshal方法呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38620151/

相关文章:

javascript - jade 在迭代中获取对象键名

javascript - 如何使用angularjs将数据添加到json数组的特定索引

jquery - 访问 JSON 元素时返回 "object Object"或未定义

Python JSON解码

go - 生成数字时代码进入无限循环

templates - 模板不呈现任何内容,也没有错误,但是状态为200

python - 如何在python中处理不规则的json文件以获取CSV中的序列化值?

docker - 尝试在golang中使用exec.Command()执行docker pull时,我看不到进度条

Golang 相当于 Python 中的 `is` 运算符

go - GoLand 的运行/调试配置窗口中 `-i` 的 "Go tool arguments"选项是什么?