示例#1
0
文件: datanode.go 项目: sjarvie/GoDFS
// 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
0
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
0
文件: datanode.go 项目: sjarvie/GoDFS
// 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
0
文件: api.go 项目: namsral/crudapi
// 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
0
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
0
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
0
文件: client.go 项目: sjarvie/GoDFS
// 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
0
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
0
文件: json.go 项目: rmera/gochem
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
0
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
0
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
0
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
0
// 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
0
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
0
文件: json.go 项目: rmera/gochem
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
}
示例#16
0
文件: hijack.go 项目: mmb/fly
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,
				},
			},
		})
	}
}
示例#17
0
文件: server.go 项目: trusch/horst
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)
}
示例#18
0
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)
	}
}
示例#19
0
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(),
	})
}
示例#20
0
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
			}
		}
	}
}
示例#21
0
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
	}
}
示例#22
0
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
}
示例#23
0
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)
	}
}
示例#24
0
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
		}
	}
}
示例#25
0
文件: server.go 项目: trusch/horst
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)
}
示例#26
0
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)
}
示例#27
0
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)
}
示例#28
0
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)
}
示例#29
0
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)

}
示例#30
0
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)
}