• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang json.Encoder类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中encoding/json.Encoder的典型用法代码示例。如果您正苦于以下问题:Golang Encoder类的具体用法?Golang Encoder怎么用?Golang Encoder使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Encoder类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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


示例16: sendSize

func sendSize(enc *json.Encoder) {
	rows, cols, err := pty.Getsize(os.Stdin)
	if err == nil {
		enc.Encode(atc.HijackInput{
			TTYSpec: &atc.HijackTTYSpec{
				WindowSize: atc.HijackWindowSize{
					Columns: cols,
					Rows:    rows,
				},
			},
		})
	}
}
开发者ID:mmb,项目名称:fly,代码行数:13,代码来源:hijack.go


示例17: processUnload

func (server *Server) processUnload(msg Message, encoder *json.Encoder) {
	if payload, ok := msg.Payload.(map[string]interface{}); ok {
		if id, ok := payload["id"].(string); ok {
			server.runner.UnloadProcessor(id)
			msg.Command = successString
			encoder.Encode(msg)
			return
		}
	}
	msg.Command = errorString
	msg.Payload = "need object with id as payload"
	encoder.Encode(msg)
}
开发者ID:trusch,项目名称:horst,代码行数:13,代码来源:server.go


示例18: sendQueueFailureResponse

func sendQueueFailureResponse(reason string, enc *json.Encoder) {
	resp := make([]interface{}, 2)
	resperr := new(string)
	*resperr = "Error"
	resp[0] = resperr
	if reason != "" {
		resp[1] = &reason
	}
	err := enc.Encode(resp)
	if nil != err {
		o.Warn("Couldn't encode response to audience: %s", err)
	}
}
开发者ID:kuroneko,项目名称:Orchestra,代码行数:13,代码来源:audience.go


示例19: Submit

func Submit(encoder *json.Encoder, email, url, content string) {
	job, err := J.New(email, url, content)
	if err != nil {
		HandleSubmitError(encoder, err)
		return
	}

	job.Progress("Working...")
	app.Queue(*job)
	encoder.Encode(JSON{
		"message": "Submitted! Hang tight...",
		"id":      job.Key.String(),
	})
}
开发者ID:yindeming,项目名称:ForrestFire,代码行数:14,代码来源:app.go


示例20: parseStream

func (sm *StreamManager) parseStream(streamDecoder *json.Decoder, streamEncoder *json.Encoder) error {
	for {
		var decodedJson map[string]interface{}
		if e := streamDecoder.Decode(&decodedJson); e != nil {
			log.Debug(e)
			return e
		}
		if _, ok := sm.IncludeFilter[decodedJson["type"].(string)]; ok || len(sm.IncludeFilter) == 0 {
			if e := streamEncoder.Encode(&decodedJson); e != nil {
				log.Debug(e)
				return e
			}
		}
	}
}
开发者ID:JFrogDev,项目名称:jfrog-cli-go,代码行数:15,代码来源:streammanager.go



注:本文中的encoding/json.Encoder类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang json.Marshaler类代码示例发布时间:2022-05-24
下一篇:
Golang json.Decoder类代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap