Esempio n. 1
5
func (h *UploadHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	oa := CheckAuthorized(w, r, false)
	if oa == nil {
		return
	}
	if r.Method != "POST" {
		http.Redirect(w, r, "/", http.StatusFound)
		return
	}
	m, _, err := r.FormFile("server")
	if err != nil {
		http.Error(w, err.Error(), http.StatusNotFound)
		return
	}
	defer m.Close()
	dst, err := os.Create(deployFileName)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	_, err = io.Copy(dst, m)
	dst.Close()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	finfo, _ := os.Stat(deployFileName)

	w.WriteHeader(200)
	w.Write([]byte("Uploaded: " + humanize.Bytes(uint64(finfo.Size()))))

}
Esempio n. 2
1
// Create a new user and store that user. Once successfully concluded a JWT
// access token will be returned to the user
func register(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	type payload struct {
		Email    string
		Password string
	}

	pl := payload{}
	decoder := json.NewDecoder(r.Body)
	err := decoder.Decode(&pl)
	if err != nil {
		http.Error(w, "Could not read the given request body", http.StatusBadRequest)
		return
	}

	user, goAuthErr := userService.Register(pl.Email, pl.Password)
	if goAuthErr != nil {
		http.Error(w, goAuthErr.Message, goAuthErr.Status)
		return
	}

	response, err := authResponse(user)
	if err != nil {
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.Write(response)
}
Esempio n. 3
1
func wrapBasicAuth(handler http.Handler, credential string) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		token := strings.SplitN(r.Header.Get("Authorization"), " ", 2)

		if len(token) != 2 || strings.ToLower(token[0]) != "basic" {
			w.Header().Set("WWW-Authenticate", `Basic realm="GoTTY"`)
			http.Error(w, "Bad Request", http.StatusUnauthorized)
			return
		}

		payload, err := base64.StdEncoding.DecodeString(token[1])
		if err != nil {
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
			return
		}

		if credential != string(payload) {
			w.Header().Set("WWW-Authenticate", `Basic realm="GoTTY"`)
			http.Error(w, "authorization failed", http.StatusUnauthorized)
			return
		}

		log.Printf("Basic Authentication Succeeded: %s", r.RemoteAddr)
		handler.ServeHTTP(w, r)
	})
}
Esempio n. 4
0
func (ths *ImageTagServer) go_get_image(w http.ResponseWriter, r *http.Request) {
	path := r.URL.Query().Get("path")
	path = ths.imgRoot + path
	path = strings.Replace(path, "..", "", -1)

	info, infoErr := os.Stat(path)
	if infoErr != nil {
		http.Error(w, infoErr.Error(), http.StatusInternalServerError)
		return
	}

	if info.IsDir() == true {
		http.Error(w, "No an image", http.StatusBadRequest)
		return
	}

	img, err := imaging.Open(path)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Header().Add("Content-Type", "image/jpeg")
	err = imaging.Encode(w, img, imaging.JPEG)
	if err != nil {
		http.Error(w, "Failed to thumbNail image", http.StatusInternalServerError)
		return
	}

}
Esempio n. 5
0
func (c *ClassifierHandler) ServeHTTP(w http.ResponseWriter,
	req *http.Request) {
	sample := core.NewSample()
	if req.Method != "POST" {
		http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
		return
	}
	features := req.FormValue("features")
	if len(features) == 0 {
		http.Error(w, "need input features", http.StatusInternalServerError)
		return
	}
	fs := make(map[string]float64)
	err := json.Unmarshal([]byte(features), &fs)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	for k, v := range fs {
		f := core.Feature{
			Id:    util.Hash(k),
			Value: v,
		}
		sample.AddFeature(f)
	}
	p := c.classifier.Predict(sample)
	output, err := json.Marshal(map[string]interface{}{
		"prediction": p,
	})
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	fmt.Fprint(w, output)
}
Esempio n. 6
0
func (s *apiService) postDBIgnores(w http.ResponseWriter, r *http.Request) {
	qs := r.URL.Query()

	bs, err := ioutil.ReadAll(r.Body)
	r.Body.Close()
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}

	var data map[string][]string
	err = json.Unmarshal(bs, &data)
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}

	err = s.model.SetIgnores(qs.Get("folder"), data["ignore"])
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}

	s.getDBIgnores(w, r)
}
Esempio n. 7
0
func (s *DockerServer) serviceCreate(w http.ResponseWriter, r *http.Request) {
	var config swarm.ServiceSpec
	defer r.Body.Close()
	err := json.NewDecoder(r.Body).Decode(&config)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	s.cMut.Lock()
	defer s.cMut.Unlock()
	s.swarmMut.Lock()
	defer s.swarmMut.Unlock()
	if len(s.nodes) == 0 || s.swarm == nil {
		http.Error(w, "no swarm nodes available", http.StatusNotAcceptable)
		return
	}
	if config.Name == "" {
		config.Name = s.generateID()
	}
	for _, s := range s.services {
		if s.Spec.Name == config.Name {
			http.Error(w, "there's already a service with this name", http.StatusConflict)
			return
		}
	}
	service := swarm.Service{
		ID:   s.generateID(),
		Spec: config,
	}
	s.addTasks(&service, false)
	s.services = append(s.services, &service)
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(service)
}
Esempio n. 8
0
File: server.go Progetto: upwrd/sift
func (s *Server) setComponentHTTP(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	devID := vars["devID"]
	compID := vars["compID"]
	if devID == "" || compID == "" {
		http.Error(w, "must provide device ID and component ID", http.StatusBadRequest)
		return
	}

	// Get the body of the request, which should contain a json-encoded Component
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "error reading request body: "+err.Error(), http.StatusBadRequest)
		return
	}

	// Parse the request as a Component
	asComponent, err := componentFromJSON(body)
	if err != nil {
		http.Error(w, "unable to interpret request body as valid Component: "+err.Error(), http.StatusBadRequest)
		return
	}

	s.setComponent(devID, compID, asComponent)
	http.Redirect(w, r, "/devices/"+devID+"/"+compID, http.StatusSeeOther)
}
Esempio n. 9
0
func encodeHandler(response http.ResponseWriter, request *http.Request, db Database, baseURL string) {
	decoder := json.NewDecoder(request.Body)
	var data struct {
		URL string `json:"url"`
	}
	err := decoder.Decode(&data)
	if err != nil {
		http.Error(response, `{"error": "Unable to parse json"}`, http.StatusBadRequest)
		return
	}

	if !govalidator.IsURL(data.URL) {
		http.Error(response, `{"error": "Not a valid URL"}`, http.StatusBadRequest)
		return
	}

	id, err := db.Save(data.URL)
	if err != nil {
		log.Println(err)
		return
	}
	resp := map[string]string{"url": strings.Replace(path.Join(baseURL, encode(id)), ":/", "://", 1), "id": encode(id), "error": ""}
	jsonData, _ := json.Marshal(resp)
	response.Write(jsonData)

}
Esempio n. 10
0
func (i *Incident) Get(w http.ResponseWriter, r *http.Request) {
	w.Header().Add("content-type", "application/json")
	vars := mux.Vars(r)
	id, ok := vars["id"]
	if !ok {
		http.Error(w, "Must append incident id", http.StatusBadRequest)
		return
	}
	index := i.pipeline.GetIndex()

	// if the id is "*", fetch all outstanding incidents
	if id == "*" {
		all := index.ListIncidents()
		all = reduceStatusAbove(event.WARNING, all)
		buff, err := json.Marshal(makeKV(all))
		if err != nil {
			logrus.Error(err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		w.Write(buff)
		return
	}

	// write out the found incident. The value will be null if nothing was found
	in := index.GetIncident([]byte(id))
	buff, err := json.Marshal(in)
	if err != nil {
		logrus.Error(err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Write(buff)
}
Esempio n. 11
0
func uploadHandler(w http.ResponseWriter, r *http.Request) {
	r.ParseMultipartForm(32 << 20)
	file, handler, err := r.FormFile("files")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer file.Close()

	f, err := os.OpenFile("./uploads/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer f.Close()
	io.Copy(f, file)

	files := Files{
		File{Name: handler.Filename, Type: handler.Header["Content-Type"][0]},
	}

	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusOK)

	if err := json.NewEncoder(w).Encode(files); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

}
Esempio n. 12
0
// dirHandler serves a directory listing for the requested path, rooted at basePath.
func dirHandler(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path == "/favicon.ico" {
		http.Error(w, "not found", 404)
		return
	}
	const base = "."
	name := filepath.Join(base, r.URL.Path)

	if isDoc(name) {
		err := renderDoc(w, name)
		if err != nil {
			log.Errorln(err)
			http.Error(w, err.Error(), 500)
		}
		return
	}
	if isDir, err := dirList(w, name); err != nil {
		log.Errorln(err)
		http.Error(w, err.Error(), 500)
		return
	} else if isDir {
		return
	}
	http.FileServer(http.Dir(*f_root)).ServeHTTP(w, r)
}
Esempio n. 13
0
func postRegister(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	username, password := r.PostFormValue("username"), r.PostFormValue("password")
	if !recaptcher.Verify(*r) {
		logger.WithFields(logrus.Fields{
			"user":  username,
			"error": recaptcher.LastError(),
		}).Error("Failed to verify reCaptcha during registration.")
		w.Write([]byte("Failed to verify the reCaptcha. Please verify that you are human and try again."))
		return
	}

	err := users.Register(username, password)
	switch err {
	case nil:
		//Success
		logger.WithFields(logrus.Fields{
			"method": r.Method,
			"url":    r.URL,
			"client": r.RemoteAddr,
			"user":   username,
		}).Info("User registration")
		renderer.Render(w, pages.Get(RegistrationSuccessPage))
	case ErrUserExists:
		http.Error(w, "The user already exists. Please try again with a different username.", http.StatusPreconditionFailed)
	default:
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}
Esempio n. 14
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. 15
0
File: server.go Progetto: upwrd/sift
func (s *Server) setDeviceHTTP(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	id := vars["devID"]
	if id == "" {
		http.Error(w, "must provide device ID", http.StatusBadRequest)
		return
	}

	// Get the body of the request, which should contain a json-encoded Device
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "error reading request body: "+err.Error(), http.StatusBadRequest)
		return
	}

	// Parse the request as a Device
	asDevice, err := deviceFromJSON(body)
	if err != nil {
		http.Error(w, "unable to interpret request body as valid Device: "+err.Error(), http.StatusBadRequest)
		return
	}

	s.SetDevice(id, asDevice)
	http.Redirect(w, r, "/devices/"+id, http.StatusSeeOther)
}
Esempio n. 16
0
func handleSearch(res http.ResponseWriter, req *http.Request) {
	ctx := appengine.NewContext(req)
	query := req.FormValue("q")
	model := &searchModel{
		Query: query,
	}

	index, err := search.Open("movies")
	if err != nil {
		http.Error(res, err.Error(), 500)
		return
	}

	iterator := index.Search(ctx, query, nil)
	for {
		var movie Movie
		_, err := iterator.Next(&movie)
		if err == search.Done {
			break
		} else if err != nil {
			http.Error(res, err.Error(), 500)
			return
		}
		model.Movies = append(model.Movies, movie)
	}

	err = tpl.ExecuteTemplate(res, "search", model)
	if err != nil {
		http.Error(res, err.Error(), 500)
		return
	}
}
Esempio n. 17
0
File: server.go Progetto: upwrd/sift
func (s *Server) getComponentHTTP(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	devID := vars["devID"]
	compID := vars["compID"]
	if devID == "" || compID == "" {
		http.Error(w, "must provide device ID and component ID", http.StatusBadRequest)
		return
	}

	device, ok := s.devices[devID]
	if !ok {
		http.Error(w, "device "+devID+" not found", http.StatusNotFound)
		return
	}
	comp, ok := device.Components[compID]
	if !ok {
		http.Error(w, "component "+compID+" not found on device "+devID, http.StatusNotFound)
		return
	}

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

	writePretty(w, asJSON, http.StatusOK)
}
Esempio n. 18
0
// ServeHTTP builds the context and passes onto the real handler
func (h handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	// Create the context
	ctx, err := NewContext(req)
	if err != nil {
		log.LogError("Failed to create context: %v", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer ctx.Close()

	// Run the handler, grab the error, and report it
	buf := new(httpbuf.Buffer)
	log.LogTrace("Web: %v %v %v %v", req.RemoteAddr, req.Proto, req.Method, req.RequestURI)
	err = h(buf, req, ctx)
	if err != nil {
		log.LogError("Error handling %v: %v", req.RequestURI, err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// Save the session
	if err = ctx.Session.Save(req, buf); err != nil {
		log.LogError("Failed to save session: %v", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// Apply the buffered response to the writer
	buf.Apply(w)
}
Esempio n. 19
0
func pubHandler(w http.ResponseWriter, req *http.Request) {
	name := req.FormValue("topic")
	if name == "" {
		http.Error(w, "missing topic", 403)
		return
	}
	size, err := strconv.Atoi(req.FormValue("size"))
	if err != nil {
		http.Error(w, err.Error(), 403)
		return
	}

	var (
		msg    *message.Ins
		header message.Header
		msgs   = make([]*message.Ins, 0, size)
	)
	for !logex.Equal(err, io.EOF) {
		msg, err = message.ReadMessage(&header, req.Body, message.RF_DEFAULT)
		if err != nil {
			break
		}
		msgs = append(msgs, msg)
	}

	t, err := getTopic(name)
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}
	t.PutSync(msgs)
	w.Write([]byte("hello"))
}
Esempio n. 20
0
func handleOauth2Callback(res http.ResponseWriter, req *http.Request) {
	ctx := appengine.NewContext(req)
	api := NewGithubAPI(ctx)
	// get the session
	session := getSession(ctx, req)

	state := req.FormValue("state")
	code := req.FormValue("code")

	if state != session.State {
		http.Error(res, "invalid state", 401)
		return
	}

	accessToken, err := api.getAccessToken(state, code)
	if err != nil {
		http.Error(res, err.Error(), 500)
		return
	}
	api.accessToken = accessToken

	username, err := api.getUsername()
	if err != nil {
		http.Error(res, err.Error(), 500)
		return
	}

	session.Username = username
	session.AccessToken = accessToken
	putSession(ctx, res, session)

	delayedGetStats.Call(ctx, accessToken, username)
	http.Redirect(res, req, "/github-info", 302)

}
Esempio n. 21
0
func (s *DockerServer) nodeUpdate(w http.ResponseWriter, r *http.Request) {
	s.swarmMut.Lock()
	defer s.swarmMut.Unlock()
	if s.swarm == nil {
		w.WriteHeader(http.StatusNotAcceptable)
		return
	}
	id := mux.Vars(r)["id"]
	var n *swarm.Node
	for i := range s.nodes {
		if s.nodes[i].ID == id {
			n = &s.nodes[i]
			break
		}
	}
	if n == nil {
		w.WriteHeader(http.StatusNotFound)
		return
	}
	var spec swarm.NodeSpec
	err := json.NewDecoder(r.Body).Decode(&spec)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	n.Spec = spec
	err = s.runNodeOperation(s.swarmServer.URL(), nodeOperation{
		Op:   "update",
		Node: *n,
	})
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}
Esempio n. 22
0
func DateHandler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	c.Infof("cs253: Requested URL: %v", r.URL)
	c.Infof("cs253: Http METHOD: %v", r.Method)
	if r.Method == "GET" {
		date := Date{
			Month: "",
			Day:   "",
			Year:  "",
		}
		if err := dateTemplate.Execute(w, date); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	} else if r.Method == "POST" {
		d := Date{
			Month: validMonth(r.FormValue("month")),
			Day:   validDay(r.FormValue("day")),
			Year:  validYear(r.FormValue("year")),
		}
		if d.Day == "" || d.Month == "" || d.Year == "" {
			d.Error = "That's an error!"
			if err := dateTemplate.Execute(w, d); err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
		}
		http.Redirect(w, r, "/unit1/thanks", http.StatusFound)
	} else {
		tools.Error404(w)
		return
	}
}
Esempio n. 23
0
func (s *apiService) postDBScan(w http.ResponseWriter, r *http.Request) {
	qs := r.URL.Query()
	folder := qs.Get("folder")
	if folder != "" {
		nextStr := qs.Get("next")
		next, err := strconv.Atoi(nextStr)
		if err == nil {
			s.model.DelayScan(folder, time.Duration(next)*time.Second)
		}

		subs := qs["sub"]
		err = s.model.ScanFolderSubdirs(folder, subs)
		if err != nil {
			http.Error(w, err.Error(), 500)
			return
		}
	} else {
		errors := s.model.ScanFolders()
		if len(errors) > 0 {
			http.Error(w, "Error scanning folders", 500)
			sendJSON(w, errors)
			return
		}
	}
}
Esempio n. 24
0
func ServeCastQuestionVote(store datastores.AnswerStoreServices) m.HandlerFunc {
	return func(c *m.Context, w http.ResponseWriter, r *http.Request) {
		vote := 1
		urlParams := mux.Vars(r)

		if urlParams["vote"] == "downvote" {
			vote = -1
		}

		voteRecipient, err, statusCode := store.CastVote(urlParams["questionID"], vote)
		if err != nil {
			http.Error(w, err.Error(), statusCode)
		}

		rep, err := c.RepStore.FindRep(urlParams["category"], voteRecipient)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
		if rep <= MAX_REP {
			c.RepStore.UpdateRep(urlParams["category"], voteRecipient, 1)
		}

		err, statusCode = store.AssessAnswers(urlParams["questionID"])
		if err != nil {
			http.Error(w, err.Error(), statusCode)
		}
	}
}
Esempio n. 25
0
func main() {
	fmt.Println("TEMP DIR:", os.TempDir())
	http.ListenAndServe(":8080", http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
		if req.Method == "POST" {
			sourc, _, err := req.FormFile("my-file")
			if err != nil {
				http.Error(res, err.Error(), 500)
				return
			}
			defer sourc.Close()

			dest, err := os.Create(filepath.Join(os.TempDir(), "file.txt"))
			if err != nil {
				http.Error(res, err.Error(), 500)
				return
			}
			defer dest.Close()

			io.Copy(dest, sourc)
		}

		res.Header().Set("Content-Type", "text/html; charset=utf-8")
		io.WriteString(res, `
      <form method="POST" enctype="multipart/form-data">
        <input type="file" name="my-file">
        <input type="submit">
      </form>
      `)
	}))
}
Esempio n. 26
0
func schedules(w http.ResponseWriter, r *http.Request) {
	minUnits, err := strconv.Atoi(r.FormValue("minUnits"))
	if err != nil {
		minUnits = 0
	}

	maxUnits, err := strconv.Atoi(r.FormValue("maxUnits"))
	if err != nil {
		maxUnits = math.MaxInt32
	}

	schedules, err := generateSchedulesJSON([]byte(r.FormValue("classes")),
		minUnits, maxUnits)

	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	t, err := texttemplate.ParseFiles("schedules.html")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	t.Execute(w, schedules)
}
Esempio n. 27
0
func (ss *StoreServer) createVolumeHandler(w http.ResponseWriter, r *http.Request) {
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	var volIDIP VolumeIDIP
	if err = json.Unmarshal(body, &volIDIP); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	id := volIDIP.ID
	volIDStr := fmt.Sprintf("%d", id)
	volPath := filepath.Join(ss.volumeDir, volIDStr+".vol")
	needleMapPath := filepath.Join(ss.volumeDir, fmt.Sprintf("needle_map_vol%d", id))
	file, err := os.OpenFile(volPath, os.O_RDWR|os.O_CREATE, 0644)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	v, err := storage.NewVolume(id, file, needleMapPath, ss.garbageThreshold)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	ss.localVolIDIPs = append(ss.localVolIDIPs, volIDIP)
	bytes, err := json.Marshal(ss.localVolIDIPs)
	if err = ioutil.WriteFile(filepath.Join(ss.volumeDir, "volIDIPs.json"), bytes, 0644); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
	ss.volumeMap[id] = v
}
Esempio n. 28
0
func deleteData(res http.ResponseWriter, req *http.Request) {
	ctx := appengine.NewContext(req)
	u := user.Current(ctx)
	keyVal := req.FormValue("keyVal")
	key, err := datastore.DecodeKey(keyVal)
	if err != nil {
		http.Error(res, "Invalid data", http.StatusBadRequest)
		log.Warningf(ctx, err.Error())
		return
	}
	var l list
	err = datastore.Get(ctx, key, &l)
	if err != nil {
		http.Error(res, "Invalid data", http.StatusBadRequest)
		log.Warningf(ctx, err.Error())
		return
	}
	if l.Owner != u.Email {
		http.Error(res, "Not authorized to delete this entry", http.StatusUnauthorized)
		log.Warningf(ctx, err.Error())
		return
	}
	err = datastore.Delete(ctx, key)
	if err != nil {
		http.Error(res, "Server Error", http.StatusInternalServerError)
		log.Errorf(ctx, err.Error())
		return
	}
}
Esempio n. 29
0
func (ths *ImageTagServer) add_tag(w http.ResponseWriter, r *http.Request) {

	tag := r.URL.Query().Get("tag")
	desc := r.URL.Query().Get("description")

	db := ths.get_db()
	if db == nil {
		http.Error(w, "DataBase error.", http.StatusInternalServerError)
		return
	}
	defer db.Close()

	res, resErr := db.Exec("INSERT INTO Tags(Tag,Description) VALUES('" + tag + "','" + desc + "');")
	if resErr != nil {
		log.Println(resErr.Error())
		http.Error(w, resErr.Error(), http.StatusInternalServerError)
		return
	}

	c, _ := res.RowsAffected()
	if c < 1 {
		log.Println("No tag added")
		http.Error(w, "No tag added", http.StatusInternalServerError)
		return
	}

	log.Println("Tag: " + tag + " added with success.")
}
Esempio n. 30
0
func (h *ManagerOptions) ServeHTTP(
	w http.ResponseWriter, req *http.Request) {
	requestBody, err := ioutil.ReadAll(req.Body)
	if err != nil {
		msg := fmt.Sprintf("rest_manage:"+
			" could not read request body err: %v", err)
		http.Error(w, msg, 400)
		return
	}

	opt := h.mgr.Options()
	newOptions := map[string]string{}
	for k, v := range opt {
		newOptions[k] = v
	}
	err = json.Unmarshal(requestBody, newOptions)
	if err != nil {
		msg := fmt.Sprintf("rest_manage:"+
			" error in unmarshalling err: %v", err)
		http.Error(w, msg, 400)
		return
	}

	h.mgr.SetOptions(newOptions)
	MustEncode(w, struct {
		Status string `json:"status"`
	}{Status: "ok"})
}