Esempio n. 1
0
func getIntegrationPipe(req Request) Response {
	workspaceID := currentWorkspaceID(req.r)
	serviceID := mux.Vars(req.r)["service"]
	if !serviceType.MatchString(serviceID) {
		return badRequest("Missing or invalid service")
	}
	pipeID := mux.Vars(req.r)["pipe"]
	if !pipeType.MatchString(pipeID) {
		return badRequest("Missing or invalid pipe")
	}

	pipe, err := loadPipe(workspaceID, serviceID, pipeID)
	if err != nil {
		return internalServerError(err.Error())
	}
	if pipe == nil {
		pipe = NewPipe(workspaceID, serviceID, pipeID)
	}

	pipe.PipeStatus, err = loadPipeStatus(workspaceID, serviceID, pipeID)
	if err != nil {
		return internalServerError(err.Error())
	}

	return ok(pipe)
}
Esempio n. 2
0
func (h *handler) joinactivity(w http.ResponseWriter, r *http.Request) {
	logr(w, r)
	h.m.Lock()
	defer h.m.Unlock()
	uid := mux.Vars(r)["uid"]
	u, err := h.getuserbyid(uid)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	aid := mux.Vars(r)["aid"]
	a, err := h.getactivitybyid(aid)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if len(a.Parts) >= a.Cap {
		http.Error(w, "activity already full", http.StatusBadRequest)
		return
	}
	for _, id := range a.Parts {
		if id == u.Id {
			http.Error(w, "user already part of activity", http.StatusBadRequest)
			return
		}
	}
	a.Parts = append(a.Parts, u.Id)
	doOK(w, r)
}
Esempio n. 3
0
func ServeSubmitAnswer(store datastores.AnswerStoreServices) m.HandlerFunc {
	return func(c *m.Context, w http.ResponseWriter, r *http.Request) {

		questionID := mux.Vars(r)["questionID"]
		isSlotAvailable, err := store.IsAnswerSlotAvailable(questionID)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		} else if !isSlotAvailable {
			http.Error(w, "Maximum capacity for answers has been reached", http.StatusForbidden)
			return
		}

		newAnswer := c.ParsedModel.(*models.Answer)
		requiredRep, err := c.RepStore.FindRep(mux.Vars(r)["category"], c.UserID)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}

		err, statusCode := store.StoreAnswer(questionID, c.UserID, newAnswer.Content, services.CalculateCurrentAnswerEligibilityRep(requiredRep))
		if err != nil {
			http.Error(w, err.Error(), statusCode)
			return
		}

		w.WriteHeader(http.StatusCreated)
	}
}
Esempio n. 4
0
func apiVMAddressRdns(w http.ResponseWriter, r *http.Request, userId int, requestBytes []byte) {
	vmId, err := strconv.Atoi(mux.Vars(r)["id"])
	if err != nil {
		http.Error(w, "Invalid VM ID", 400)
		return
	}
	vm := vmGetUser(userId, vmId)
	if vm == nil {
		http.Error(w, "No virtual machine with that ID", 404)
		return
	}

	var request api.VMAddressRdnsRequest
	err = json.Unmarshal(requestBytes, &request)
	if err != nil {
		http.Error(w, "Invalid json: "+err.Error(), 400)
		return
	}

	err = vm.SetRdns(mux.Vars(r)["ip"], request.Hostname)
	if err != nil {
		http.Error(w, err.Error(), 400)
	} else {
		apiResponse(w, 200, nil)
	}
}
Esempio n. 5
0
func (ctx *Context) GetTagsHandler(w http.ResponseWriter, r *http.Request) {
	namespace := mux.Vars(r)["namespace"]
	repository := mux.Vars(r)["repository"]

	data := make(map[string]string)

	dir, err := ctx.storage.ListDirectory(storage.TagPath(namespace, repository))
	if err != nil {
		sendResponse(w, "Repository not found", 404, nil, false)
		return
	}

	for _, fname := range dir {
		tagName := filepath.Base(fname)
		if !strings.HasPrefix(tagName, "tag_") {
			continue
		}

		content, err := ctx.storage.GetContent(fname)
		if err != nil {
			continue
		}
		data[tagName[4:]] = string(content)
	}

	sendResponse(w, data, 200, nil, false)
}
Esempio n. 6
0
func deleteBuildCommentHandler(w http.ResponseWriter, r *http.Request) {
	defer timer.New("deleteBuildCommentHandler").Stop()
	if !userHasEditRights(r) {
		util.ReportError(w, r, fmt.Errorf("User does not have edit rights."), "User does not have edit rights.")
		return
	}
	w.Header().Set("Content-Type", "application/json")
	cache, err := getCommitCache(w, r)
	if err != nil {
		return
	}
	buildId, err := strconv.ParseInt(mux.Vars(r)["buildId"], 10, 32)
	if err != nil {
		util.ReportError(w, r, err, fmt.Sprintf("Invalid build id: %v", err))
		return
	}
	commentId, err := strconv.ParseInt(mux.Vars(r)["commentId"], 10, 32)
	if err != nil {
		util.ReportError(w, r, err, fmt.Sprintf("Invalid comment id: %v", err))
		return
	}
	if err := cache.DeleteBuildComment(int(buildId), int(commentId)); err != nil {
		util.ReportError(w, r, err, fmt.Sprintf("Failed to delete comment: %v", err))
		return
	}
}
Esempio n. 7
0
func appGet(h func(http.ResponseWriter, *http.Request, *schema.PodManifest, *schema.ImageManifest)) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		token := mux.Vars(r)["token"]

		an := mux.Vars(r)["app"]
		if an == "" {
			w.WriteHeader(http.StatusBadRequest)
			fmt.Fprint(w, "app missing")
			return
		}

		pm, im, err := pods.getManifests(token, an)
		switch {
		case err == nil:
			h(w, r, pm, im)

		case err == errPodNotFound:
			w.WriteHeader(http.StatusUnauthorized)
			fmt.Fprintln(w, err)

		default:
			w.WriteHeader(http.StatusNotFound)
			fmt.Fprintln(w, err)
		}
	}
}
Esempio n. 8
0
// taskTimeStatisticsHandler is a handler for task time aggretations.
// it essentially acts as a wrapper for task.AverageTaskTimeDifference
func (uis *UIServer) taskTimeStatisticsHandler(w http.ResponseWriter, r *http.Request) {
	field1 := mux.Vars(r)["field1"]
	field2 := mux.Vars(r)["field2"]
	groupyBy := mux.Vars(r)["group_by"]
	cutoffDaysAsString := mux.Vars(r)["cutoff_days"]
	cutoffDays, err := strconv.Atoi(cutoffDaysAsString)
	if err != nil {
		uis.LoggedError(w, r, http.StatusBadRequest, fmt.Errorf("Error converting cutoff_days to integer: %v", err))
		return
	}

	var cutoff time.Time
	// -1 is passed to represent "All Time", otherwise the number
	// is an amount of days to include in the aggregation
	if cutoffDays < 0 {
		cutoff = time.Unix(1, 0) // 1 more than 0 time to ignore unset time fields
	} else {
		cutoff = time.Now().Add(time.Duration(-1*cutoffDays) * time.Hour * 24)
	}

	timeMap, err := task.AverageTaskTimeDifference(field1, field2, groupyBy, cutoff)
	if err != nil {
		uis.LoggedError(w, r, http.StatusInternalServerError, fmt.Errorf("Error computing time stats: %v", err))
		return
	}

	var timeList []uiTaskTimeStatistic
	for id, val := range timeMap {
		timeList = append(timeList, uiTaskTimeStatistic{id, val})
	}
	uis.WriteJSON(w, http.StatusOK, timeList)
}
Esempio n. 9
0
func Start() {

	r := mux.NewRouter()

	// Gitchain API
	r.Methods("POST").Path("/rpc").HandlerFunc(jsonRpcService().ServeHTTP)
	r.Methods("GET").Path("/info").HandlerFunc(info)

	// Git Server
	r.Methods("POST").Path("/{path}/git-upload-pack").HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
		body, _ := ioutil.ReadAll(req.Body)
		fmt.Println(req, body)
		resp.Write([]byte(mux.Vars(req)["path"]))
	})

	r.Methods("POST").Path("/{path}/git-receive-pack").HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
		fmt.Println(req)
		resp.Write([]byte(mux.Vars(req)["path"]))
	})

	r.Methods("GET").Path("/{path}/info/refs").HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
		body, _ := ioutil.ReadAll(req.Body)
		fmt.Println(req, body)

		resp.Write([]byte(mux.Vars(req)["path"]))
	})

	http.Handle("/", r)

	err := http.ListenAndServe(fmt.Sprintf("127.0.0.1:%d", env.Port), nil)
	if err != nil {
		log.Fatal(err)
	}
}
Esempio n. 10
0
func (api *Api) pluginUnsubsribe(rw http.ResponseWriter, r *http.Request, user *account.User) {
	service, err := account.FindServiceBySubdomain(mux.Vars(r)["subdomain"])
	if err != nil {
		handleError(rw, err)
		return
	}

	_, err = findTeamAndCheckUser(service.Team, user)
	if err != nil {
		handleError(rw, err)
		return
	}

	plugin, err := account.FindPluginByNameAndService(mux.Vars(r)["plugin_name"], *service)
	if err != nil {
		handleError(rw, err)
		return
	}

	if err = plugin.Delete(); err != nil {
		handleError(rw, err)
		return
	}

	Ok(rw, plugin)
}
Esempio n. 11
0
func VerifyTargetHandler(w http.ResponseWriter, req *http.Request) {
	if !checkAuth(req, authuser, authpassword) {
		UnauthorizedResponse(w)
		return
	}

	hostname1 := dns.Fqdn(mux.Vars(req)["hostname1"])
	hostname2 := dns.Fqdn(mux.Vars(req)["hostname2"])
	nocache := req.URL.Query().Get("nocache") != ""

	target_alias := req.URL.Query().Get("target_alias")
	if target_alias != "" {
		target_alias = dns.Fqdn(target_alias)
	}

	vr, err := VerifyTarget(hostname1, hostname2, target_alias, nocache)
	if err != nil {
		w.WriteHeader(500)
		json.NewEncoder(w).Encode(vr.Error)
		return
	}

	json.NewEncoder(w).Encode(vr)
	return
}
Esempio n. 12
0
// getTask finds a json document by using thex task that is in the plugin.
func getTaskByName(w http.ResponseWriter, r *http.Request) {
	t := plugin.GetTask(r)
	if t == nil {
		http.Error(w, "task not found", http.StatusNotFound)
		return
	}
	name := mux.Vars(r)["name"]
	taskName := mux.Vars(r)["task_name"]

	var jsonForTask TaskJSON
	err := db.FindOneQ(collection, db.Query(bson.M{VersionIdKey: t.Version, BuildIdKey: t.BuildId, NameKey: name,
		TaskNameKey: taskName}), &jsonForTask)
	if err != nil {
		if err == mgo.ErrNotFound {
			plugin.WriteJSON(w, http.StatusNotFound, nil)
			return
		}
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if len(r.FormValue("full")) != 0 { // if specified, include the json data's container as well
		plugin.WriteJSON(w, http.StatusOK, jsonForTask)
		return
	}
	plugin.WriteJSON(w, http.StatusOK, jsonForTask.Data)
}
Esempio n. 13
0
func deletePipeSetup(req Request) Response {
	workspaceID := currentWorkspaceID(req.r)
	serviceID := mux.Vars(req.r)["service"]
	if !serviceType.MatchString(serviceID) {
		return badRequest("Missing or invalid service")
	}
	pipeID := mux.Vars(req.r)["pipe"]
	if !pipeType.MatchString(pipeID) {
		return badRequest("Missing or invalid pipe")
	}

	pipe, err := loadPipe(workspaceID, serviceID, pipeID)
	if err != nil {
		return internalServerError(err.Error())
	}
	if pipe == nil {
		return badRequest("Pipe is not configured")
	}

	if err := pipe.destroy(workspaceID); err != nil {
		return internalServerError(err.Error())
	}

	return ok(nil)
}
Esempio n. 14
0
func postPipeSetup(req Request) Response {
	workspaceID := currentWorkspaceID(req.r)
	serviceID := mux.Vars(req.r)["service"]
	if !serviceType.MatchString(serviceID) {
		return badRequest("Missing or invalid service")
	}
	pipeID := mux.Vars(req.r)["pipe"]
	if !pipeType.MatchString(pipeID) {
		return badRequest("Missing or invalid pipe")
	}

	pipe := NewPipe(workspaceID, serviceID, pipeID)
	if err := json.Unmarshal(req.body, &pipe); err != nil {
		return internalServerError(err.Error())
	}

	if errorMsg := pipe.validate(); errorMsg != "" {
		return badRequest(errorMsg)
	}

	if err := pipe.save(); err != nil {
		return internalServerError(err.Error())
	}
	return ok(nil)
}
Esempio n. 15
0
func snapshotHandler(d *Daemon, r *http.Request) Response {
	containerName := mux.Vars(r)["name"]
	c, err := newLxdContainer(containerName, d)
	if err != nil {
		return SmartError(err)
	}

	snapshotName := mux.Vars(r)["snapshotName"]
	dir := snapshotDir(c, snapshotName)

	_, err = os.Stat(dir)
	if err != nil {
		return SmartError(err)
	}

	switch r.Method {
	case "GET":
		return snapshotGet(c, snapshotName)
	case "POST":
		return snapshotPost(r, c, snapshotName)
	case "DELETE":
		return snapshotDelete(d, c, snapshotName)
	default:
		return NotFound
	}
}
func HandleGetTrips(w http.ResponseWriter, req *http.Request) {
	fmt.Println(req.Method, " ", req.URL, " ", mux.Vars(req))

	id, _ := strconv.Atoi(mux.Vars(req)["trip_id"])

	trip, ok := _trips[id]
	if !ok {
		http.Error(w, "trip id not found", http.StatusInternalServerError)
		return
	}

	var trip_res TripResponse
	trip_res.ID = trip.id
	trip_res.STATUS = trip.status
	trip_res.STARTING_FROM_LOCATION_ID = trip.start
	trip_res.BEST_ROUTE_LOCATION_IDS = trip.routes
	trip_res.TOTAL_UBER_COST = trip.cost_estimate
	trip_res.TOTAL_UBER_DURATION = trip.duration_estimate
	trip_res.TOTAL_DISTANCE = trip.distance_estimate

	out, err := json.Marshal(trip_res)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	//
	// Write result
	//
	w.WriteHeader(http.StatusOK)
	w.Write(out)
}
Esempio n. 17
0
func ListPushHandler(rw http.ResponseWriter, req *http.Request) {
	key := mux.Vars(req)["key"]
	value := mux.Vars(req)["value"]
	list := simpleredis.NewList(pool, key)
	HandleError(nil, list.Add(value))
	ListRangeHandler(rw, req)
}
Esempio n. 18
0
// GET /{network}/leases/subnet?next=cursor
func handleWatchLease(ctx context.Context, sm subnet.Manager, w http.ResponseWriter, r *http.Request) {
	network := mux.Vars(r)["network"]
	if network == "_" {
		network = ""
	}

	sn := subnet.ParseSubnetKey(mux.Vars(r)["subnet"])
	if sn == nil {
		w.WriteHeader(http.StatusBadRequest)
		fmt.Fprint(w, "bad subnet")
		return
	}

	cursor := getCursor(r.URL)

	wr, err := sm.WatchLease(ctx, network, *sn, cursor)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		fmt.Fprint(w, err)
		return
	}

	switch wr.Cursor.(type) {
	case string:
	case fmt.Stringer:
		wr.Cursor = wr.Cursor.(fmt.Stringer).String()
	default:
		w.WriteHeader(http.StatusInternalServerError)
		fmt.Fprint(w, fmt.Errorf("internal error: watch cursor is of unknown type"))
		return
	}

	jsonResponse(w, http.StatusOK, wr)
}
Esempio n. 19
0
func handleRegisterApp(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()

	uuid, err := types.NewUUID(mux.Vars(r)["uuid"])
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		fmt.Fprintf(w, "UUID is missing or malformed: %v", err)
		return
	}

	an := mux.Vars(r)["app"]
	if an == "" {
		w.WriteHeader(http.StatusBadRequest)
		fmt.Fprint(w, "app missing")
		return
	}

	im := &schema.ImageManifest{}
	if err := json.NewDecoder(r.Body).Decode(im); err != nil {
		w.WriteHeader(http.StatusBadRequest)
		fmt.Fprintf(w, "JSON-decoding failed: %v", err)
		return
	}

	err = pods.addApp(uuid, an, im)
	if err != nil {
		w.WriteHeader(http.StatusNotFound)
		fmt.Fprint(w, "Pod with given UUID not found")
		return
	}

	w.WriteHeader(http.StatusOK)
}
Esempio n. 20
0
func (m *ManifestPlugin) GetManifest(w http.ResponseWriter, r *http.Request) {
	project := mux.Vars(r)["project_id"]
	revision := mux.Vars(r)["revision"]

	version, err := version.FindOne(version.ByProjectIdAndRevision(project, revision))
	if err != nil {
		http.Error(w, fmt.Sprintf("error getting version for project %v with revision %v: %v",
			project, revision, err), http.StatusBadRequest)
		return
	}
	if version == nil {
		http.Error(w, fmt.Sprintf("version not found for project %v, with revision %v", project, revision),
			http.StatusNotFound)
		return
	}

	foundManifest, err := manifest.FindOne(manifest.ById(version.Id))
	if err != nil {
		http.Error(w, fmt.Sprintf("error getting manifest with version id %v: %v",
			version.Id, err), http.StatusBadRequest)
		return
	}
	if foundManifest == nil {
		http.Error(w, fmt.Sprintf("manifest not found for version %v", version.Id), http.StatusNotFound)
		return
	}
	plugin.WriteJSON(w, http.StatusOK, foundManifest)
	return

}
Esempio n. 21
0
func handleAppAnnotation(w http.ResponseWriter, r *http.Request, pm *schema.PodManifest, im *schema.ImageManifest) {
	defer r.Body.Close()

	n := mux.Vars(r)["name"]
	k, err := types.NewACIdentifier(n)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		fmt.Fprintf(w, "App annotation name %q is not a valid AC Identifier", n)
		return
	}

	n = mux.Vars(r)["app"]
	an, err := types.NewACName(n)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		fmt.Fprintf(w, "App name %q is not a valid AC Name", n)
		return
	}

	merged := mergeAppAnnotations(im, pm, an)

	v, ok := merged.Get(k.String())
	if !ok {
		w.WriteHeader(http.StatusNotFound)
		fmt.Fprintf(w, "App annotation %q not found", k)
		return
	}

	w.Header().Add("Content-Type", "text/plain")
	w.WriteHeader(http.StatusOK)
	w.Write([]byte(v))
}
Esempio n. 22
0
func deleteCard(w http.ResponseWriter, r *http.Request) {
	// Get deck id from the url
	deckId, err := parseObjectId(mux.Vars(r)["did"])
	if err != nil {
		http.Error(w, "", http.StatusNotFound)
		return
	}

	// Get the card number to delete
	cardId, err := parseObjectId(mux.Vars(r)["cid"])
	if err != nil {
		http.Error(w, "", http.StatusBadRequest)
		return
	}

	q := bson.M{
		"$pull": bson.M{"cards": bson.M{"id": cardId}},
	}
	err = decks.UpdateId(deckId, q)
	if err != nil {
		if err == mgo.ErrNotFound {
			http.Error(w, "", http.StatusNotFound)
			return
		}
		http.Error(w, "", http.StatusInternalServerError)
		return
	}

	w.WriteHeader(http.StatusOK)
}
Esempio n. 23
0
func makeHttpHandler(eng *engine.Engine, logging bool, localMethod string, localRoute string, handlerFunc HttpApiFunc, enableCors bool, dockerVersion version.Version) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// log the request
		utils.Debugf("Calling %s %s", localMethod, localRoute)

		if logging {
			log.Println(r.Method, r.RequestURI)
		}

		if strings.Contains(r.Header.Get("User-Agent"), "Docker-Client/") {
			userAgent := strings.Split(r.Header.Get("User-Agent"), "/")
			if len(userAgent) == 2 && !dockerVersion.Equal(version.Version(userAgent[1])) {
				utils.Debugf("Warning: client and server don't have the same version (client: %s, server: %s)", userAgent[1], dockerVersion)
			}
		}
		version := version.Version(mux.Vars(r)["version"])
		if version == "" {
			version = api.APIVERSION
		}
		if enableCors {
			writeCorsHeaders(w, r)
		}

		if version.GreaterThan(api.APIVERSION) {
			http.Error(w, fmt.Errorf("client and server don't have same version (client : %s, server: %s)", version, api.APIVERSION).Error(), http.StatusNotFound)
			return
		}

		if err := handlerFunc(eng, version, w, r, mux.Vars(r)); err != nil {
			utils.Errorf("Handler for %s %s returned error: %s", localMethod, localRoute, err)
			httpError(w, err)
		}
	}
}
Esempio n. 24
0
func (h *Handler) LoginHandler(res http.ResponseWriter, req *http.Request) {
	if mux.Vars(req)["id"] != "" {
		h.initiateLogin("/topics/"+mux.Vars(req)["id"], res, req)
	} else {
		h.initiateLogin("/topics", res, req)
	}
}
Esempio n. 25
0
func (ctx *Context) PutTagHandler(w http.ResponseWriter, r *http.Request) {
	namespace := mux.Vars(r)["namespace"]
	repository := mux.Vars(r)["repository"]
	tag := mux.Vars(r)["tag"]

	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		sendResponse(w, "Couldn't read request body", 500, nil, false)
		return
	}

	var data string
	if err := json.Unmarshal(body, &data); err != nil {
		sendResponse(w, "Invalid data", 400, nil, false)
		return
	}

	exists, err := ctx.storage.Exists(storage.ImageJsonPath(data))
	if !exists || err != nil {
		sendResponse(w, "Image not found", 404, nil, false)
		return
	}

	ctx.storage.PutContent(storage.TagPathWithName(namespace, repository, tag), []byte(data))

	sendResponse(w, data, 200, nil, false)
}
Esempio n. 26
0
func createGraphHandler(fs iFileSystem) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		filename := "graphs/" + mux.Vars(r)["id"] + ".json"
		if _, err := fs.Stat(filename); fs.IsNotExist(err) {
			fileContent := "{}"
			newGraph, err := ioutil.ReadAll(r.Body)
			if err != nil {
				log.Println(err)
				w.WriteHeader(http.StatusInternalServerError)
				return
			}
			if len(newGraph) > 0 {
				fileContent, err = p.LivesplitXMLtoJSON(string(newGraph))
				if err != nil {
					w.WriteHeader(http.StatusBadRequest)
					return
				}
			}
			httpStatus, err := createFile(fs, filename, fileContent)
			if err == nil {
				pwFilename := "passwords/" + mux.Vars(r)["id"] + ".txt"
				httpStatus, err = createFile(fs, pwFilename, mux.Vars(r)["pw"])
				if err != nil {
					removeErr := fs.Remove(filename)
					if removeErr != nil {
						log.Println(removeErr)
					}
				}
			}
			w.WriteHeader(httpStatus)
			return
		}
		w.WriteHeader(http.StatusConflict)
	}
}
Esempio n. 27
0
func HandlerId(response http.ResponseWriter, request *http.Request) {
	fmt.Println(request.Method)
	fmt.Println("Entrou no handlerId")

	switch request.Method {
	case "GET":
		vars := mux.Vars(request)
		id := bson.ObjectIdHex(vars["id"])

		prova := GetProva(id)
		fmt.Println(prova)
		js, _ := json.MarshalIndent(prova, " ", "   ")
		response.Write(js)

	case "POST":
		var prova Prova
		json.NewDecoder(request.Body).Decode(&prova)
		fmt.Println("prova.Id")
		if prova.Id == "" {
			err := Insere(&prova)
			fmt.Println(err)
		} else {
			err := Update(&prova)
			fmt.Println(err)
		}

	case "DELETE":
		vars := mux.Vars(request)
		id := bson.ObjectIdHex(vars["id"])
		err := Delete(id)
		fmt.Println(err)
	}
}
func HandleGetLocation(w http.ResponseWriter, req *http.Request) {
	fmt.Println(req.Method, " ", req.URL, " ", mux.Vars(req))

	id, _ := strconv.Atoi(mux.Vars(req)["loc_id"])

	c, session, err := OpenCollection("locations")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer session.Close()

	loc, err := GetLocation(c, id)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	lat, lng, err := GetMapsLocation(loc)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	loc.lat = strconv.FormatFloat(lat, 'f', 6, 64)
	loc.lng = strconv.FormatFloat(lng, 'f', 6, 64)

	out, err := json.Marshal(JSON(loc))
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Write(out)
}
Esempio n. 29
0
func makeHttpHandler(srv *Server, logging bool, localMethod string, localRoute string, handlerFunc HttpApiFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// log the request
		utils.Debugf("Calling %s %s", localMethod, localRoute)

		if logging {
			log.Println(r.Method, r.RequestURI)
		}

		if strings.Contains(r.Header.Get("User-Agent"), "Docker-Client/") {
			userAgent := strings.Split(r.Header.Get("User-Agent"), "/")
			if len(userAgent) == 2 && userAgent[1] != VERSION {
				utils.Debugf("Warning: client and server don't have the same version (client: %s, server: %s)", userAgent[1], VERSION)
			}
		}
		version, err := strconv.ParseFloat(mux.Vars(r)["version"], 64)
		if err != nil {
			version = APIVERSION
		}
		if srv.runtime.config.EnableCors {
			writeCorsHeaders(w, r)
		}

		if version == 0 || version > APIVERSION {
			w.WriteHeader(http.StatusNotFound)
			return
		}

		if err := handlerFunc(srv, version, w, r, mux.Vars(r)); err != nil {
			utils.Errorf("Error: %s", err)
			httpError(w, err)
		}
	}
}
Esempio n. 30
0
func DeleteApiFileName(w http.ResponseWriter, r *http.Request) {

	//Get vars
	roomId := mux.Vars(r)["roomid"]
	filename := mux.Vars(r)["filename"]
	filepath := *dataDir + "/" + roomId + "/" + filename

	//Check if room exists
	if _, err := os.Stat(filepath); os.IsNotExist(err) {
		w.Header().Set("Content-Type", "application/json; charset=UTF-8")
		w.WriteHeader(http.StatusNotFound)
		if err := json.NewEncoder(w).Encode(jsonErr{Code: http.StatusNotFound, Text: "Not Found"}); err != nil {
			panic(err)
		}
	}

	//Delete file
	os.Remove(filepath)

	m := Message{
		"OK",
	}
	if err := json.NewEncoder(w).Encode(m); err != nil {
		panic(err)
	}
}