當前位置: 首頁>>代碼示例>>Golang>>正文


Golang json.Encoder類代碼示例

本文整理匯總了Golang中encoding/json.Encoder的典型用法代碼示例。如果您正苦於以下問題:Golang Encoder類的具體用法?Golang Encoder怎麽用?Golang Encoder使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了Encoder類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: SendHeartbeat

// SendHeartbeat is used to notify the namenode of a valid connection
// on a periodic basis
func SendHeartbeat(encoder *json.Encoder) {
	p := new(Packet)
	p.SRC = id
	p.DST = "NN"
	p.CMD = HB
	encoder.Encode(p)
}
開發者ID:sjarvie,項目名稱:GoDFS,代碼行數:9,代碼來源:datanode.go

示例2: ServeHTTP

func (m *MemberTrashListHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
	var memberlist []*membersys.MemberWithKey
	var enc *json.Encoder
	var err error

	if !m.auth.IsAuthenticatedScope(req, m.admingroup) {
		rw.WriteHeader(http.StatusUnauthorized)
		return
	}

	memberlist, err = m.database.EnumerateTrashedMembers(
		req.FormValue("start"), m.pagesize)
	if err != nil {
		log.Print("Error enumerating trashed members: ", err)
		rw.WriteHeader(http.StatusInternalServerError)
		rw.Write([]byte("Error enumerating trashed members: " + err.Error()))
		return
	}

	rw.Header().Set("Content-Type", "application/json; encoding=utf8")
	enc = json.NewEncoder(rw)
	if err = enc.Encode(memberlist); err != nil {
		log.Print("Error JSON encoding member list: ", err)
		rw.WriteHeader(http.StatusInternalServerError)
		rw.Write([]byte("Error encoding result: " + err.Error()))
		return
	}
}
開發者ID:starshipfactory,項目名稱:membersys,代碼行數:28,代碼來源:trash.go

示例3: HandleResponse

// HandleResponse delegates actions to perform based on the
// contents of a recieved Packet, and encodes a response
func HandleResponse(p Packet, encoder *json.Encoder) {
	r := new(Packet)
	r.SRC = id
	r.DST = p.SRC

	switch p.CMD {
	case ACK:
		return
	case LIST:
		list := GetBlockHeaders()
		r.Headers = make([]BlockHeader, len(list))

		for i, b := range list {
			r.Headers[i] = b
		}
		r.CMD = LIST
	case BLOCK:
		r.CMD = BLOCKACK
		WriteBlock(p.Data)
		r.Headers = make([]BlockHeader, 0, 2)
		r.Headers = append(r.Headers, p.Data.Header)

	case RETRIEVEBLOCK:
		fmt.Println("retrieving block from ", p.Headers[0])
		b := BlockFromHeader(p.Headers[0])
		r.CMD = BLOCK
		r.Data = b
	}
	encoder.Encode(*r)
}
開發者ID:sjarvie,項目名稱:GoDFS,代碼行數:32,代碼來源:datanode.go

示例4: authenticateAndAuthorize

// authenticate request and authorize action
func authenticateAndAuthorize(action Action, urlVars map[string]string, params url.Values, resp http.ResponseWriter, enc *json.Encoder) (ok bool) {
	authenticated, client, errorMessage := g.Authenticate(params)
	if !authenticated {
		log.Println("unauthenticated request:\n\tURL parameters:", params, "\n\terror message:", errorMessage)

		resp.WriteHeader(http.StatusUnauthorized)
		err := enc.Encode(apiResponse{errorMessage, "", nil})
		if err != nil {
			log.Println(err)
		}

		return
	}

	kind := urlVars["kind"]
	id := urlVars["id"]
	authorized, errorMessage := g.Authorize(client, action, urlVars)
	if !authorized {
		log.Println("unauthorized request:\n\tclient:", client, "\n\taction:", action, "kind:", kind, "id:", id, "\n\terror message", errorMessage)

		resp.WriteHeader(http.StatusForbidden)
		err := enc.Encode(apiResponse{errorMessage, "", nil})
		if err != nil {
			log.Println(err)
		}

		return
	}

	ok = true
	return
}
開發者ID:namsral,項目名稱:crudapi,代碼行數:33,代碼來源:api.go

示例5: create

func create(storage Storage, resp http.ResponseWriter, vars map[string]string, enc *json.Encoder, dec *json.Decoder) {
	var resource map[string]interface{}
	err := dec.Decode(&resource)

	if err != nil {
		log.Println(err)

		resp.WriteHeader(http.StatusBadRequest)
		err = enc.Encode(apiResponse{"malformed json", "", nil})
		if err != nil {
			log.Println(err)
		}

		return
	}

	// set in storage
	id, stoResp := storage.Create(vars["collection"], resource)

	// write response
	resp.WriteHeader(stoResp.StatusCode())
	err = enc.Encode(apiResponse{stoResp.Error(), id, nil})
	if err != nil {
		log.Println(err)
	}
}
開發者ID:sauerbraten,項目名稱:crudapi,代碼行數:26,代碼來源:api.go

示例6: catchReturn

func catchReturn(dataChan chan Data, encoder *json.Encoder, id int) {
	select {
	case data := <-dataChan:
		fmt.Println("Got message back!", data)
		data["Id"] = id
		encoder.Encode(&data)
	}
}
開發者ID:lafisrap,項目名稱:21tweet,代碼行數:8,代碼來源:connector.go

示例7: SendPackets

// SendPackets encodes packets and transmits them to their proper recipients
func SendPackets(encoder *json.Encoder, ch chan Packet) {
	for p := range ch {
		err := encoder.Encode(p)
		if err != nil {
			log.Println("error sending", p.DST)
		}
	}
}
開發者ID:sjarvie,項目名稱:GoDFS,代碼行數:9,代碼來源:client.go

示例8: UploadProfilePic

func UploadProfilePic(wr http.ResponseWriter, req *http.Request) {
	var (
		profileImgLoc string
		id            int64
		err           error
		p             *data.Profile
		file          multipart.File
		header        *multipart.FileHeader
		enc           *json.Encoder
	)

	enc = json.NewEncoder(wr)
	params := mux.Vars(req)
	id, err = strconv.ParseInt(params["id"], 10, 64)
	p, err = data.FindProfileById(id)
	req.ParseMultipartForm(10 << 20) //approx 10MB
	file, header, err = req.FormFile("file")

	handleUploadErr := func(err error, status int) {
		if nil != err {
			wr.WriteHeader(status)
			enc.Encode(NewErrorJSON(err.Error(), status))
		}
	}

	if err != nil {
		log.Println("error upload pic " + err.Error())
		handleUploadErr(err, http.StatusBadRequest)
		return
	}
	defer file.Close()
	uploadedFilePath, err := service.SaveUploadedFile(file, header.Filename)
	if err != nil {
		log.Println("failed to create thumbnail file  " + err.Error())
		handleUploadErr(err, http.StatusInternalServerError)
		return
	}

	uploadedFilePath, err = service.ThumbnailMultipart(file, header.Filename)
	if err != nil {
		log.Println("failed to create thumbnail file  " + err.Error())
		handleUploadErr(err, http.StatusInternalServerError)
		return
	}

	profileImgLoc, err = data.PutInBucket(uploadedFilePath, header.Filename)

	if err != nil {
		log.Println("failed up upload to s3 " + err.Error())
		handleUploadErr(err, http.StatusInternalServerError)
		return
	}

	p.UpdateProfilePic(profileImgLoc)
	enc.Encode(p)

}
開發者ID:maleck13,項目名稱:locals-api,代碼行數:57,代碼來源:profile.go

示例9: EncodeCoords

func EncodeCoords(coords *v3.Matrix, enc *json.Encoder) *Error {
	c := new(Coords)
	t := make([]float64, 3, 3)
	for i := 0; i < coords.NVecs(); i++ {
		c.Coords = coords.Row(t, i)
		if err := enc.Encode(c); err != nil {
			return NewError("postprocess", "chemjson.EncodeCoords", err)
		}
	}
	return nil
}
開發者ID:rmera,項目名稱:gochem,代碼行數:11,代碼來源:json.go

示例10: sendLocalResp

func sendLocalResp(enc *json.Encoder, resp minicli.Responses, more bool) error {
	r := miniclient.Response{
		More: more,
	}
	if resp != nil {
		r.Resp = resp
		r.Rendered = resp.String()
	}

	return enc.Encode(&r)
}
開發者ID:cdshann,項目名稱:minimega,代碼行數:11,代碼來源:command_socket.go

示例11: formatJson

func formatJson(jw *json.Encoder, lim int, a ...interface{}) {
	var jr jrec
	if lim > 0 {
		jr.Truncated = truncate(lim, a)
	}
	jr.Msg = a
	err := jw.Encode(jr)
	if err != nil {
		log.Fatal("json.Encode: ", err)
	}
}
開發者ID:csabahenk,項目名稱:parsefuse,代碼行數:11,代碼來源:parsefuse.go

示例12: getAll

func getAll(storage Storage, resp http.ResponseWriter, vars map[string]string, enc *json.Encoder, dec *json.Decoder) {
	// look for resources
	resources, stoResp := storage.GetAll(vars["collection"])

	// write response
	resp.WriteHeader(stoResp.StatusCode())
	err := enc.Encode(apiResponse{stoResp.Error(), "", resources})
	if err != nil {
		log.Println(err)
	}
}
開發者ID:sauerbraten,項目名稱:crudapi,代碼行數:11,代碼來源:api.go

示例13: del

// delete() is a built-in function, thus del() is used here
func del(storage Storage, resp http.ResponseWriter, vars map[string]string, enc *json.Encoder, dec *json.Decoder) {
	// delete resource
	stoResp := storage.Delete(vars["collection"], vars["id"])

	// write response
	resp.WriteHeader(stoResp.StatusCode())
	err := enc.Encode(apiResponse{stoResp.Error(), "", nil})
	if err != nil {
		log.Println(err)
	}
}
開發者ID:sauerbraten,項目名稱:crudapi,代碼行數:12,代碼來源:api.go

示例14: sendLocalResp

func sendLocalResp(enc *json.Encoder, resp minicli.Responses, more bool) error {
	log.Infoln("sending resp:", resp)
	r := localResponse{
		More: more,
	}
	if resp != nil {
		r.Resp = resp
		r.Rendered = resp.String()
	}

	return enc.Encode(&r)
}
開發者ID:ITLivLab,項目名稱:minimega,代碼行數:12,代碼來源:command_socket.go

示例15: EncodeAtoms

func EncodeAtoms(mol chem.Atomer, enc *json.Encoder) *Error {
	const funcname = "EncodeAtoms"
	if mol == nil {
		return nil //Its assumed to be intentional.
	}
	for i := 0; i < mol.Len(); i++ {
		if err := enc.Encode(mol.Atom(i)); err != nil {
			return NewError("postprocess", funcname, err)
		}
	}
	return nil
}
開發者ID:rmera,項目名稱:gochem,代碼行數:12,代碼來源:json.go


注:本文中的encoding/json.Encoder類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。