Beispiel #1
1
// AddFileHandler adds the file path to the database. It should be usually be given to an POST endpoint
// with id as the parameter
// Ex: /file/:id
func AddFileHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	decoder := json.NewDecoder(r.Body)
	// TODO: ps is there for checking emptiness. Should be replaced
	var js, ps jsonStruct
	if err := decoder.Decode(&js); err != nil || js == ps {
		w.WriteHeader(400)
		return
	}

	couchServer, err := couchdb.NewClient("http://127.0.0.1:5984", nil)
	db, _ := couchServer.CreateDB("files")
	userID := memberlist.DefaultWANConfig().Name

	_, err = db.Put(p.ByName("id"), file{UUID: uuid.NewV4().String(), Fname: path.Base(js.Path), UserID: userID}, "")
	if err != nil {
		w.WriteHeader(500)
		fmt.Fprint(w, err)
		return
	}

	// TODO: Send 409 for conflict
	if err := AddFile(p.ByName("id"), js.Path); err != nil {
		w.WriteHeader(500)
		fmt.Fprint(w, err)
		return
	}

	w.WriteHeader(201)
}
Beispiel #2
0
// servePutService creates a service.
func (h *Handler) servePutService(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
	// Retrieve the path parameter.
	service := params.ByName("service")
	if err := ValidServiceName(service); err != nil {
		hh.ValidationError(w, "", err.Error())
		return
	}

	// Read config from the request.
	config := &discoverd.ServiceConfig{}
	if err := hh.DecodeJSON(r, config); err != nil {
		hh.Error(w, err)
		return
	}

	// Add the service to the store.
	if err := h.Store.AddService(service, config); err == ErrNotLeader {
		h.redirectToLeader(w, r)
		return
	} else if IsServiceExists(err) {
		hh.ObjectExistsError(w, err.Error())
		return
	} else if err != nil {
		hh.Error(w, err)
		return
	}
}
Beispiel #3
0
func GrantVoteResponse(rw http.ResponseWriter, req *http.Request, p httprouter.Params) {
	vote = p.ByName("vote")
	//ch <- 1
	fmt.Println("Vote received:", vote)
	if vote == "true" {
		voteCount++
	}
	fmt.Println(voteCount)
	if voteCount > total/2 && state != "leader" {
		fmt.Println("Leader....")
		state = "leader"
		myDetails := MyDetails{}
		myDetails.IsLeader = true
		myDetails.IP = "localhost" //enter the IP address
		myDetails.Port = "3001"    //enter the port number
		myDeatilsInJSON, _ := json.Marshal(myDetails)
		myDetailsBuff := new(bytes.Buffer)
		err := binary.Write(myDetailsBuff, binary.BigEndian, &myDeatilsInJSON)
		if err != nil {
			fmt.Errorf("Error in request API: %v", err)
		}
		url := fmt.Sprintf("http://localhost:9999/setleader")
		client := http.Client{}
		req, _ := http.NewRequest("POST", url, myDetailsBuff)
		res, _ := client.Do(req)
		res.Body.Close()
		NotifyFollowers() //DK
	}
}
Beispiel #4
0
// Raw stats: Entries from eugo_raw for the last 24 hours
// This file is getting a bit long
//
func rawStats(res http.ResponseWriter, req *http.Request, ps httprouter.Params) {
	from := func() int64 {
		urlPS, _ := url.ParseQuery(req.URL.RawQuery)
		param, ok := urlPS["from"]

		if ok {
			ts, err := strconv.ParseInt(param[0], 10, 64)
			if err == nil {
				return ts
			}
		}

		return (time.Now().UTC().UnixNano() / 1e6) - 864e5
	}()

	key := ps.ByName("key")
	rawStats, err := getRawStats(key, from)
	if err != nil {
		res.WriteHeader(http.StatusInternalServerError)
		return
	}

	jsonHandler(res, req, rawStats)
	return
}
Beispiel #5
0
// GetUser retrieves an individual user resource
func (uc UserController) GetUser(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	// Grab id
	id := p.ByName("id")

	// Verify id is ObjectId, otherwise bail
	if !bson.IsObjectIdHex(id) {
		w.WriteHeader(404)
		return
	}

	// Grab id
	oid := bson.ObjectIdHex(id)

	// Stub user
	u := models.User{}

	// Fetch user
	if err := uc.session.DB("go_rest_tutorial").C("users").FindId(oid).One(&u); err != nil {
		w.WriteHeader(404)
		return
	}

	// Marshal provided interface into JSON structure
	uj, _ := json.Marshal(u)

	// Write content-type, statuscode, payload
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(200)
	fmt.Fprintf(w, "%s", uj)
}
Beispiel #6
0
func GetTrips(rw http.ResponseWriter, req *http.Request, p httprouter.Params) {

	fmt.Println("Hello world")
	session, err := mgo.Dial("mongodb://*****:*****@ds045054.mongolab.com:45054/mydatabase")
	if err != nil {
		panic(err)
	}
	defer session.Close()

	// Optional. Switch the session to a monotonic behavior.
	session.SetMode(mgo.Monotonic, true)

	c := session.DB("mydatabase").C("UberResult")

	id := p.ByName("name")
	Oid := bson.ObjectIdHex(id)
	var UberGetResult UberPostRequest
	c.FindId(Oid).One(&UberGetResult)

	if err != nil {
		log.Fatal(err)
	}

	b2, err := json.Marshal(UberGetResult)
	if err != nil {
	}
	rw.WriteHeader(http.StatusOK)

	fmt.Fprintf(rw, string(b2))
}
Beispiel #7
0
Datei: user.go Projekt: ryanj/dex
func (s *UserMgmtServer) resendInvitationEmail(w http.ResponseWriter, r *http.Request, ps httprouter.Params, creds api.Creds) {
	id := ps.ByName("id")
	if id == "" {
		writeAPIError(w, http.StatusBadRequest, newAPIError(errorInvalidRequest, "id is required"))
		return
	}
	resendEmailInvitationReq := schema.ResendEmailInvitationRequest{}
	if err := json.NewDecoder(r.Body).Decode(&resendEmailInvitationReq); err != nil {
		writeInvalidRequest(w, "cannot parse JSON body")
		return
	}

	redirURL, err := url.Parse(resendEmailInvitationReq.RedirectURL)
	if err != nil {
		writeAPIError(w, http.StatusBadRequest,
			newAPIError(errorInvalidRequest, "redirectURL must be a valid URL"))
		return
	}

	resendEmailInvitationResponse, err := s.api.ResendEmailInvitation(creds, id, *redirURL)
	if err != nil {
		s.writeError(w, err)
		return
	}

	writeResponseWithBody(w, http.StatusOK, resendEmailInvitationResponse)
}
Beispiel #8
0
// MusicUpsert function
func MusicUpsert(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
	log.Println("access to user put api")

	id := params.ByName("id")

	if id == "" {
		log.Print("put without _id")
	} else {
		log.Print("put with id")
	}

	if r.Body != nil {
		defer r.Body.Close()
		var data model.Music

		body, _ := ioutil.ReadAll(r.Body)
		if err := json.Unmarshal([]byte(body), &data); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
		// 	http.Error(w, err.Error(), http.StatusInternalServerError)
		// 	return
		// }

		if err := db.Upsert(musicColname, data.ID, data); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/json")
		w.Write([]byte("{\"status\":\"ok\"}"))
	}
}
Beispiel #9
0
func (c *ChatService) onGetChatHistory(w http.ResponseWriter, req *http.Request, p httprouter.Params) {
	log.Println("Get chat history...")
	groupId := p.ByName("id")

	queryParams := req.URL.Query()
	var offset uint = 0
	var limit uint = 20

	if o, err := strconv.ParseUint(queryParams.Get("offset"), 10, 32); err == nil {
		offset = uint(o)
	}

	if l, err := strconv.ParseUint(queryParams.Get("limit"), 10, 32); err == nil {
		limit = uint(l)
	}

	log.Println("Limit =", limit, "Offset =", offset)
	log, err := c.chatStore.GetMessagesFor(groupId, offset, limit)
	if err == nil {
		response := make(map[string]interface{})
		response["limit"] = limit
		response["offset"] = offset
		response["messages"] = log
		response["id"] = groupId
		json.NewEncoder(w).Encode(response)
	} else {
		w.WriteHeader(http.StatusInternalServerError)
		json.NewEncoder(w).Encode(ErrorMessage{
			Error: err.Error(),
		})
	}
}
Beispiel #10
0
func (a *Admin) handleDelete(rw http.ResponseWriter, req *http.Request, ps httprouter.Params) {
	slug := ps.ByName("slug")
	model, ok := a.models[slug]
	if !ok {
		http.NotFound(rw, req)
		return
	}

	id := 0
	if idStr := ps.ByName("id"); len(idStr) > 0 {
		var err error
		id, err = parseInt(idStr)
		if err != nil {
			return
		}
	}

	err := model.delete(id)
	sess := a.getUserSession(req)
	if err == nil {
		sess.addMessage("success", fmt.Sprintf("%v has been deleted.", model.Name))
	} else {
		sess.addMessage("warning", err.Error())
	}

	url, _ := a.urls.URL("view", slug)
	http.Redirect(rw, req, url, 302)
	return
}
Beispiel #11
0
func deletePhoto(w http.ResponseWriter, r *http.Request) {
	// Get session
	sess := session.Instance(r)

	var params httprouter.Params
	params = context.Get(r, "params").(httprouter.Params)
	//userid := params.ByName("userid")
	//userid := uint64(site_idInt)
	userid := uint64(sess.Values["id"].(uint32))

	picid := params.ByName("picid")

	err := model.PhotoDelete(userid, picid)
	if err != nil {
		log.Println(err)
		sess.AddFlash(view.Flash{"An error occurred on the server. Please try again later.", view.FlashError})
		sess.Save(r, w)
	} else {

		/*err = os.Remove(photoPath + fmt.Sprintf("%v", userid) + "/" + picid + ".jpg")
		if err != nil {
			log.Println(err)
		}*/

		sess.AddFlash(view.Flash{"Photo removed!", view.FlashSuccess})
		sess.Save(r, w)
	}
}
func (uc UserController) GetUser(rw http.ResponseWriter, req *http.Request, p httprouter.Params) {
	// Grab id
	id := p.ByName("location_id")

	// Verify id is ObjectId, otherwise bail
	if !bson.IsObjectIdHex(id) {
		rw.WriteHeader(404)
		return
	}

	// Grab id
	oid := bson.ObjectIdHex(id)

	// Stub user
	u := UserLocation{}
	// Fetch user
	if err := uc.session.DB("mongodatabase").C("CMPE273").FindId(oid).One(&u); err != nil {
		rw.WriteHeader(404)
		return
	}

	// Marshal provided interface into JSON structure
	uj, _ := json.Marshal(u)

	// Write content-type, statuscode, payload
	rw.Header().Set("Content-Type", "application/json")
	rw.WriteHeader(200)
	fmt.Fprintf(rw, "%s", uj)
}
Beispiel #13
0
// Slack handles a request to publish a webhook to a Slack channel.
func (s *Server) Slack(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
	log.Printf("%s %s\n", r.Method, r.URL.RequestURI())

	if r.Method != "POST" {
		w.WriteHeader(http.StatusMethodNotAllowed)
		return
	}

	data, err := ioutil.ReadAll(r.Body)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		log.Printf("Error parsing body: %v\n", err)
	}

	event, err := webhook.Parse(data)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		log.Printf("Error parsing event: %v\n", err)
	}

	slackAlpha, slackBeta, slackGamma := params.ByName("slackAlpha"), params.ByName("slackBeta"), params.ByName("slackGamma")
	slackToken := fmt.Sprintf("%s/%s/%s", slackAlpha, slackBeta, slackGamma)

	service := &SlackService{Token: slackToken}
	text, err := service.PostEvent(event)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		log.Printf("Internal Error: %v\n", err)
	}

	fmt.Fprintln(w, text)
}
Beispiel #14
0
// servePutLeader sets the leader for a service.
func (h *Handler) servePutLeader(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
	// Retrieve path parameters.
	service := params.ByName("service")

	// Check if the service allows manual leader election.
	config := h.Store.Config(service)
	if config == nil || config.LeaderType != discoverd.LeaderTypeManual {
		hh.ValidationError(w, "", "service leader election type is not manual")
		return
	}

	// Read instance from the request.
	inst := &discoverd.Instance{}
	if err := hh.DecodeJSON(r, inst); err != nil {
		hh.Error(w, err)
		return
	}

	// Manually set the leader on the service.
	if err := h.Store.SetServiceLeader(service, inst.ID); err == ErrNotLeader {
		h.redirectToLeader(w, r)
		return
	} else if err != nil {
		hh.Error(w, err)
		return
	}
}
Beispiel #15
0
// servePutInstance adds an instance to a service.
func (h *Handler) servePutInstance(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
	// Read path parameter.
	service := params.ByName("service")

	// Read instance from request.
	inst := &discoverd.Instance{}
	if err := json.NewDecoder(r.Body).Decode(inst); err != nil {
		hh.Error(w, err)
		return
	}

	// Ensure instance is valid.
	if err := inst.Valid(); err != nil {
		hh.ValidationError(w, "", err.Error())
		return
	}

	// Add instance to service in the store.
	if err := h.Store.AddInstance(service, inst); err == ErrNotLeader {
		h.redirectToLeader(w, r)
		return
	} else if IsNotFound(err) {
		hh.ObjectNotFoundError(w, err.Error())
		return
	} else if err != nil {
		hh.Error(w, err)
		return
	}
}
Beispiel #16
0
// GetUser retrieves an individual user resource
func (uc UserController) GetUser(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	// Get the user's id from the parameters
	id := p.ByName("id")

	// Check to ensure that this is a BSON object
	if !bson.IsObjectIdHex(id) {
		w.WriteHeader(404)
		return
	}

	// Grab the object's id
	oid := bson.ObjectIdHex(id)

	// Stub an example user
	u := models.User{}

	// Fetch the user data
	if err := uc.session.DB("go-deploy").C("users").FindId(oid).One(&u); err != nil {
		w.WriteHeader(404)
		return
	}

	// Marshal provided interface into JSON structure
	uj, _ := json.Marshal(u)

	// Write content-type, statuscode, payload
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(200)
	fmt.Fprintf(w, "%s", uj)
}
Beispiel #17
0
// MusicDelete function
func MusicDelete(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
	log.Print("access to user delete api")

	id := params.ByName("id")

	if id == "" {
		log.Print("remove by query")

		if err := db.Remove(colname, nil); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	} else {
		log.Print("remove by id")

		if err := db.RemoveByID(musicColname, id); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(204)
	w.Write([]byte("{\"status\":\"ok\"}"))
}
func updateLocation(rw http.ResponseWriter, req *http.Request, p httprouter.Params) {

	id, err1 := strconv.Atoi(p.ByName("locid"))

	if err1 != nil {
		panic(err1)
	}
	conn, err := mgo.Dial("mongodb://*****:*****@ds045464.mongolab.com:45464/testgoogledatabase")

	if err != nil {
		panic(err)
	}
	defer conn.Close()

	conn.SetMode(mgo.Monotonic, true)
	c := conn.DB("testgoogledatabase").C("testgoogledatabase")

	decoder := json.NewDecoder(req.Body)
	var t modReqObj
	err = decoder.Decode(&t)
	if err != nil {
		fmt.Println("Error")
	}

	colQuerier := bson.M{"id": id}
	change := bson.M{"$set": bson.M{"address": t.Address, "city": t.City, "state": t.State, "zip": t.Zip}}
	err = c.Update(colQuerier, change)
	if err != nil {
		panic(err)
	}

}
Beispiel #19
0
//GET function
func get(rw http.ResponseWriter, req *http.Request, p httprouter.Params) {

	key := p.ByName("id")
	key_int, _ := strconv.Atoi(key)
	var port []string
	var response Response
	port = strings.Split(req.Host, ":")

	if port[1] == "3000" {
		response.Key = key_int
		response.Value = server1_kvalue[key_int]
	} else if port[1] == "3001" {
		response.Key = key_int
		response.Value = server2_kvalue[key_int]
	} else {
		response.Key = key_int
		response.Value = server3_kvalue[key_int]
	}

	payload, err := json.Marshal(response)
	if err != nil {
		http.Error(rw, "Bad Request", http.StatusInternalServerError)
		return
	}
	rw.Header().Set("Content-Type", "application/json")
	rw.Write(payload)
}
func getTrip(rw http.ResponseWriter, req *http.Request, p httprouter.Params) {

	conn, err := mgo.Dial("mongodb://*****:*****@ds045464.mongolab.com:45464/testgoogledatabase")

	if err != nil {
		panic(err)
	}
	defer conn.Close()

	conn.SetMode(mgo.Monotonic, true)
	c := conn.DB("testgoogledatabase").C("trips")
	result := TripResponse{}
	err = c.Find(bson.M{"id": p.ByName("tripid")}).One(&result)
	if err != nil {
		fmt.Println(err)
	}

	js, err := json.Marshal(result)
	if err != nil {
		fmt.Println("Error")
		return
	}
	rw.Header().Set("Content-Type", "application/json")
	rw.Write(js)
}
Beispiel #21
0
// @Title pixieHandler
// @Description Dictionary with kernel, intrd(s) and commandline for pixiecore
// @Param macaddr	path	string	true	"MacAddress"
// @Success 200	{object} string "Dictionary with kernel, intrd(s) and commandline for pixiecore"
// @Failure 404	{object} string "Not in build mode"
// @Failure 500	{object} string "Unable to find host definition for hostname"
// @Router /v1/boot/{macaddr} [GET]
func pixieHandler(response http.ResponseWriter, request *http.Request,
	ps httprouter.Params, config Config) {

	macaddr := ps.ByName("macaddr")
	hostname, found := config.MachineBuild[macaddr]

	if found == false {
		log.Println(found)
		http.Error(response, "Not in build mode", 404)
		return
	}

	m, err := machineDefinition(hostname, config.MachinePath)

	m.Token = config.Tokens[hostname]

	if err != nil {
		log.Println(err)
		http.Error(response, fmt.Sprintf("Unable to find host definition for %s", hostname), 500)
		return
	}

	pxeconfig, _ := m.pixieInit(config)
	result, _ := json.Marshal(pxeconfig)
	response.Write(result)

}
func getKey(rw http.ResponseWriter, req *http.Request, p httprouter.Params) {

	var response []byte
	key_id := p.ByName("key_id")
	if value, found := keyValStore[key_id]; found {
		jsonResponse := &getResponse{
			key_id,
			value,
		}
		resp, _ := json.Marshal(jsonResponse)
		response = resp
		rw.WriteHeader(200)

	} else {
		jsonResponse := &error{
			"Key does not found in the cache",
		}
		resp, _ := json.Marshal(jsonResponse)
		response = resp
		rw.WriteHeader(404)

	}

	// Write content-type, statuscode, payload
	rw.Header().Set("Content-Type", "application/json")
	rw.WriteHeader(200)
	fmt.Fprintf(rw, "%s", response)
}
Beispiel #23
0
func Getlocations(rw http.ResponseWriter, req *http.Request, p httprouter.Params) {

	session, err := mgo.Dial("mongodb://*****:*****@ds045054.mongolab.com:45054/mydatabase")
	if err != nil {
		panic(err)
	}
	defer session.Close()

	// Optional. Switch the session to a monotonic behavior.
	session.SetMode(mgo.Monotonic, true)

	c := session.DB("mydatabase").C("people")
	id := p.ByName("name")
	oid := bson.ObjectIdHex(id)
	var result MyJsonName
	c.FindId(oid).One(&result)

	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Id2:", result.Id.String())
	oid = bson.ObjectId(result.Id)

	b2, err := json.Marshal(result)
	if err != nil {
	}
	rw.WriteHeader(http.StatusOK)

	fmt.Fprintf(rw, string(b2))
	fmt.Println("Method Name: " + req.Method)
}
Beispiel #24
0
func (api *HTTPAPI) Send(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	volumeID := ps.ByName("volume_id")

	if !strings.Contains(r.Header.Get("Accept"), snapshotContentType) {
		httphelper.ValidationError(w, "", fmt.Sprintf("must be prepared to accept a content type of %q", snapshotContentType))
		return
	}
	w.Header().Set("Content-Type", snapshotContentType)

	var haves []json.RawMessage
	if err := httphelper.DecodeJSON(r, &haves); err != nil {
		httphelper.Error(w, err)
		return
	}

	err := api.vman.SendSnapshot(volumeID, haves, w)
	if err != nil {
		switch err {
		case volume.ErrNoSuchVolume:
			httphelper.ObjectNotFoundError(w, fmt.Sprintf("no volume with id %q", volumeID))
			return
		default:
			httphelper.Error(w, err)
			return
		}
	}
}
Beispiel #25
0
func WebDelete2Weeks(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	if p.ByName("secret") == "gonotes" {
		delete_gt_2weeks()
		pl("Delete should be completed at this point")
	}
	http.Redirect(w, r, "/q/all/l/100", http.StatusFound)
}
Beispiel #26
0
//Getvalueforkey of server1
func getvalueforkey(rw http.ResponseWriter, req *http.Request, p httprouter.Params) {
	intid, err := strconv.Atoi(p.ByName("key_id"))
	if err != nil {
		fmt.Printf("%s", err)
		panic(err)
	}
	valuestored, ok := cachestoremap[intid]
	if !ok {
		rw.WriteHeader(400)
		return
	}

	resp := respentry{
		Key:   intid,
		Value: valuestored,
	}
	//marshal struct to json
	repjson, err := json.Marshal(resp)
	if err != nil {
		fmt.Printf("%s", err)
		os.Exit(1)
	}
	rw.WriteHeader(200)
	fmt.Fprintf(rw, "%s", repjson)

}
Beispiel #27
0
func (a *API) GetGoalStats(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	applicationName := ps.ByName("applicationName")
	goalName := ps.ByName("goalName")
	sinceString := r.FormValue("since")

	sinceTime, err := time.Parse(time.RFC3339Nano, sinceString)

	if err != nil {
		sinceTime = time.Time{}
	}

	application, err := a.apparatchick.ApplicationByName(applicationName)

	if err != nil {
		respondWithError(err, w)
		return
	}

	stats, err := application.Stats(goalName, sinceTime)
	if err != nil {
		respondWithError(err, w)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(200)
	if err := json.NewEncoder(w).Encode(stats); err != nil {
		panic(err)
	}
}
Beispiel #28
0
func (a *API) GetGoalInspect(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	applicationName := ps.ByName("applicationName")
	goalName := ps.ByName("goalName")

	application, err := a.apparatchick.ApplicationByName(applicationName)

	if err != nil {
		respondWithError(err, w)
		return
	}

	container, err := application.Inspect(goalName)

	if err != nil {
		respondWithError(err, w)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(200)
	if err := json.NewEncoder(w).Encode(container); err != nil {
		panic(err)
	}

}
Beispiel #29
0
func readKey(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	// Simply write some test data for now
	fmt.Println("reading values")

	id := p.ByName("id")
	i, _ := strconv.Atoi(id)

	u := Data{}

	if val, ok := Resp[i]; ok {
		fmt.Println(i, val)
		u.Key = i
		u.Value = val
	}
	// Marshal provided interface into JSON structure

	fmt.Println("before marshalling map :", u)

	uj, _ := json.Marshal(u)

	fmt.Println("after marshalling map :", u)
	// Write content-type, statuscode, payload
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(200)
	fmt.Fprintf(w, "%s", uj)
}
Beispiel #30
0
// NewTxHandler handles requests to POST /item/:id/transaction
func (s *RESTServer) NewTxHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	id := ps.ByName("id")

	tx, err := s.TxStore.Create(id)
	if err != nil {
		// the err is probably that there is already a transaction open
		// on the item
		w.WriteHeader(409)
		fmt.Fprintln(w, err.Error())
		return
	}
	w.Header().Set("Location", "/transaction/"+tx.ID)
	tx.Creator = ps.ByName("username")
	// TODO(dbrower): use a limit reader to 1MB(?) for this
	var cmds [][]string
	err = json.NewDecoder(r.Body).Decode(&cmds)
	if err != nil {
		tx.SetStatus(transaction.StatusError)
		w.WriteHeader(400)
		fmt.Fprintln(w, err.Error())
		return
	}
	err = tx.AddCommandList(cmds)
	if err != nil {
		tx.SetStatus(transaction.StatusError)
		w.WriteHeader(400)
		fmt.Fprintln(w, err.Error())
		return
	}
	tx.SetStatus(transaction.StatusWaiting)
	go s.processCommit(tx)
	w.WriteHeader(202)
}