本文整理匯總了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)
}
示例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
}
}
示例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)
}
示例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
}
示例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)
}
}
示例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)
}
}
示例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)
}
}
}
示例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)
}
示例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
}
示例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)
}
示例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)
}
}
示例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)
}
}
示例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)
}
}
示例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)
}
示例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
}