在以下示例中来自 Web Development with Go by Shiju Varghese ,用于为每个 HTTP 请求使用新的 MongoDB session 来实现 HTTP 服务器:
PostCategory
函数为什么使用json
包的Decode
方法?为什么在
GetCategories
函数中使用了json
包的Marshal
方法?
一开始以为PostCategory
中的Decode
和GetCategories
中的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
) 读取,因为 NewDecoder
将 io.Reader
作为输入。
您可以使用 json.Unmarshal
,但您必须先将响应主体读入 []byte
并将该值传递给 json。解码
。 NewDecoder
在这里更方便。
关于json - 这里为什么要用到json包的Decode和Marshal方法呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38620151/