// 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) }
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 } }
// 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) }
// 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 }
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) } }
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) } }
// 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) } } }
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) }
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 }
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) }
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) } }
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) } }
// 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) } }
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) }
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 }
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, }, }, }) } }
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) }
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) } }
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(), }) }
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 } } } }
func (m *MemberDetailHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) { var user string = m.auth.GetAuthenticatedUser(req) var member *membersys.MembershipAgreement var memberid string = req.FormValue("email") var enc *json.Encoder var err error if user == "" { rw.WriteHeader(http.StatusUnauthorized) return } if len(memberid) == 0 { rw.WriteHeader(http.StatusLengthRequired) rw.Write([]byte("No email given")) return } member, err = m.database.GetMemberDetail(memberid) if err != nil { rw.WriteHeader(http.StatusInternalServerError) rw.Write([]byte("Error fetching member details: " + err.Error())) return } if member.MemberData.GetUsername() != user && len(m.admingroup) > 0 && !m.auth.IsAuthenticatedScope(req, m.admingroup) { rw.WriteHeader(http.StatusForbidden) rw.Write([]byte("Only admin users may look at other accounts")) return } // Trash the membership agreement, transmitting it over HTTP doesn't // make much sense. member.AgreementPdf = make([]byte, 0) // The password hash is off limits too. member.MemberData.Pwhash = nil rw.Header().Set("Content-Type", "application/json; encoding=utf8") enc = json.NewEncoder(rw) if err = enc.Encode(member); err != nil { rw.WriteHeader(http.StatusInternalServerError) rw.Write([]byte("Error encoding JSON structure: " + err.Error())) return } }
func encode(enc *json.Encoder, event Event) (err error) { if err = enc.Encode(event); err == nil { return } // Attempts to recover from invalid data put in the free form Event.Data field. switch err.(type) { case *json.UnsupportedTypeError, *json.UnsupportedValueError, *json.MarshalerError: event.Level = ALERT event.Info.Errors = append(event.Info.Errors, MakeEventError(err)) event.Data = EventData{"unserializable": fmt.Sprintf("%#v", event.Data)} err = enc.Encode(event) } return }
func sendQueueSuccessResponse(job *JobRequest, enc *json.Encoder) { resp := make([]interface{}, 2) resperr := new(string) *resperr = "OK" resp[0] = resperr // this probably looks odd, but all numbers cross through float64 when being json encoded. d'oh! jobid := new(uint64) *jobid = uint64(job.Id) resp[1] = jobid err := enc.Encode(resp) if nil != err { o.Warn("Couldn't encode response to audience: %s", err) } }
func streamProcessPayloads(conn connection.Connection, encoder *json.Encoder) { for { payload := &warden.ProcessPayload{} err := conn.ReadResponse(payload) if err != nil { fmt.Println("stream failed:", err) os.Exit(1) } encoder.Encode(payload) if payload.ExitStatus != nil { break } } }
func (server *Server) processDoc(msg Message, encoder *json.Encoder) { if payload, ok := msg.Payload.(map[string]interface{}); ok { if to, ok := payload["to"].(string); ok { if toIn, ok := payload["toIn"].(string); ok { if value, ok := payload["value"]; ok { server.runner.Process(to, toIn, value) msg.Command = successString encoder.Encode(msg) return } } } } msg.Command = errorString msg.Payload = "need object with to, toIn and value as payload" encoder.Encode(msg) }
func CreateProject(wr http.ResponseWriter, req *http.Request) { var ( decoder *json.Decoder encoder *json.Encoder proj *data.Project err error ) decoder = json.NewDecoder(req.Body) encoder = json.NewEncoder(wr) proj = data.NewProject() if err = decoder.Decode(proj); err != nil { log.Println(err.Error()) wr.WriteHeader(http.StatusBadRequest) encoder.Encode(NewErrorJSON(err.Error(), 400)) return } if _, err = proj.Save(); err != nil { log.Println(err.Error()) wr.WriteHeader(http.StatusInternalServerError) encoder.Encode(NewErrorJSONUnexpectedError(err.Error())) return } wr.WriteHeader(http.StatusCreated) encoder.Encode(proj) }
func GetProject(wr http.ResponseWriter, req *http.Request) { var ( encoder *json.Encoder proj *data.Project err error ) encoder = json.NewEncoder(wr) proj = data.NewProject() params := mux.Vars(req) log.Println(params) log.Println(req.URL.String()) id, err := strconv.ParseInt(params["id"], 10, 64) if err != nil { wr.WriteHeader(http.StatusBadRequest) encoder.Encode(NewErrorJSONBadRequest()) return } proj, err = proj.FindById(id) if _, ok := err.(*data.NoResult); ok { wr.WriteHeader(http.StatusNotFound) encoder.Encode(NewErrorJSONNotFound()) return } if nil != err { wr.WriteHeader(http.StatusInternalServerError) log.Println("faild to get profile " + err.Error()) return } encoder.Encode(proj) }
func UpdateProfile(wr http.ResponseWriter, req *http.Request) { var ( decoder *json.Decoder profile *data.Profile err error encoder *json.Encoder ) decoder = json.NewDecoder(req.Body) profile = data.NewProfile() encoder = json.NewEncoder(wr) if err = decoder.Decode(profile); nil != err { wr.WriteHeader(http.StatusBadRequest) encoder.Encode(NewErrorJSONBadRequest()) return } if err = profile.Update(); err != nil { log.Printf("error occurred saving profile %s ", err.Error()) wr.WriteHeader(http.StatusInternalServerError) encoder.Encode(NewErrorJSONUnexpectedError(err.Error())) return } encoder.Encode(profile) }
func CreateProfile(wr http.ResponseWriter, req *http.Request) { var ( decoder *json.Decoder profile *data.Profile err error encoder *json.Encoder ) decoder = json.NewDecoder(req.Body) profile = data.NewProfile() encoder = json.NewEncoder(wr) if err = decoder.Decode(profile); err != nil { http.Error(wr, err.Error(), http.StatusBadRequest) return } if profile.Exists(profile.Email) { wr.WriteHeader(http.StatusConflict) encoder.Encode(NewErrorJSONExists()) return } if _, err = profile.Save(); err != nil { log.Printf("error occurred saving profile %s ", err.Error()) wr.WriteHeader(http.StatusInternalServerError) encoder.Encode(NewErrorJSONUnexpectedError(err.Error())) return } encoder.Encode(profile) //get handle to email channel and send email to user go service.SendMailTemplate(service.MAIL_TEMPLATE_INTEREST, service.NewMailSender(), service.MAIL_FROM, profile.Email) }
func ListProjects(wr http.ResponseWriter, req *http.Request) { var ( from int to int err error encoder *json.Encoder proj *data.Project listProj []*data.Project ) proj = data.NewProject() encoder = json.NewEncoder(wr) f := req.URL.Query().Get("from") t := req.URL.Query().Get("to") if from, err = strconv.Atoi(f); err != nil { log.Println(err.Error()) wr.WriteHeader(http.StatusBadRequest) encoder.Encode(NewErrorJSONBadRequest()) return } if to, err = strconv.Atoi(t); err != nil { wr.WriteHeader(http.StatusBadRequest) encoder.Encode(NewErrorJSONBadRequest()) return } listProj, err = proj.ListProjects(from, to) encoder.Encode(listProj) }