Beispiel #1
0
//createFiles grava arquivos junto ao sistema de armazenamento e formata resposta para os clientes
func createFiles(appID string, files []*model.File, w http.ResponseWriter) {

	fs, err := getDefaultStorage(appID)

	if err != nil {
		results.InternalError(err, w)
		return
	}

	for _, f := range files {

		if err := fs.Add(f); err != nil {

			if err == model.ErrFileNotSupported {
				w.WriteHeader(http.StatusBadRequest)
			} else if err == model.ErrStorageLocked {
				w.WriteHeader(http.StatusForbidden)
			} else {
				w.WriteHeader(http.StatusInternalServerError)
			}

			fmt.Fprintln(w, err.Error())
			return
		}

		w.Header().Add(X_FILE_ID_HEADER, f.ID)
		w.Header().Add("Location", "/vfolder/files/"+f.ID)
	}

	w.WriteHeader(http.StatusCreated)
}
Beispiel #2
0
func handleCtrlPanel(r *mux.Router) {

	//Todas as actions vão exigir que o usuário seja o ADMIN
	r = r.PathPrefix("/admin/ctrlpanel").Subrouter()

	//Action que exibe o painel de controle padrão
	r.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {

		log.Println(LOG_NAME, "GET", req.URL.RequestURI())

		var (
			stats    map[string]*model.VFStorageStats
			appIDs   []string
			err      error
			currStat *model.VFStorageStats
		)

		stats = make(map[string]*model.VFStorageStats)
		appIDs, err = defaultStorageFactory.List()

		if err != nil {
			results.InternalError(err, w)
			return
		}

		for _, appID := range appIDs {
			grp, err := defaultStorageFactory.Get(appID)

			if err == nil {

				currStat, err = grp.Stats()

				if err == nil {
					stats[appID] = currStat
				}
			}
		}

		results.View("ctrlpanel/index", stats, w)
	})
}
Beispiel #3
0
func handleVFolder(r *mux.Router) {

	r = r.PathPrefix("/api/vfolder").Subrouter()

	get := r.Methods("GET").Subrouter()
	post := r.Methods("POST").Subrouter()

	//Action para publicar um novo arquivo através de um formulário de envio de arquivos tradicional
	post.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {

		log.Println(LOG_NAME, "POST", req.URL.RequestURI())

		var (
			files []*model.File
			err   error
			appID string
		)

		appID = getAppID(req)
		files, err = getFilesFromMultipartRequest(appID, req)

		if err != nil {
			w.WriteHeader(http.StatusBadRequest)
			fmt.Fprintln(w, err.Error())
			return
		}

		createFiles(appID, files, w)

		results.View("vfolder/created", files, w)

		serverlog.Info(appID, LOG_NAME, "NEW FILE")
	})

	//Action para publicar um novo arquivo com base no corpo da requisição
	post.HandleFunc("/{file_name}", func(w http.ResponseWriter, req *http.Request) {

		log.Println(LOG_NAME, "POST", req.URL.RequestURI())

		var (
			vars            map[string]string
			files           []*model.File
			err             error
			appID, fileName string
		)

		vars = mux.Vars(req)
		appID = getAppID(req)
		fileName = vars["file_name"]

		files, err = getFilesFromRESTRequest(appID, fileName, req)

		if err != nil {
			w.WriteHeader(http.StatusBadRequest)
			fmt.Fprintln(w, err.Error())
			return
		}

		createFiles(appID, files, w)

		serverlog.Info(appID, LOG_NAME, "NEW FILE")
	})

	//Action para listar em formato JSON uma lista de dados básicos dos arquivos de uma determinada aplicação
	get.HandleFunc("/files", func(w http.ResponseWriter, req *http.Request) {

		log.Println(LOG_NAME, "GET ", req.URL.RequestURI())

		var (
			err   error
			files []model.FileInfo
			fs    model.VFStorage
			appID string
		)

		appID = getAppID(req)
		fs, err = getDefaultStorage(appID)

		if err != nil {
			results.InternalError(err, w)
			return
		}

		files, err = fs.List()

		if err != nil {
			results.InternalError(err, w)
			return
		}

		results.Json(files, w)

		serverlog.Info(appID, LOG_NAME, "GET FILE LIST")
	})

	//Action para remover um arquivo
	r.Methods("DELETE").Subrouter().HandleFunc("/files/{id}", func(w http.ResponseWriter, req *http.Request) {

		log.Println(LOG_NAME, "DELETE ", req.URL.RequestURI())

		var (
			vars  map[string]string
			id    string
			err   error
			fs    model.VFStorage
			appID string
		)

		vars = mux.Vars(req)
		id = vars["id"]
		appID = getAppID(req)
		fs, err = getDefaultStorage(appID)

		if err != nil {
			results.InternalError(err, w)
			return
		}

		err = fs.Remove(id)

		if err != nil {

			if err == model.ErrFileNotFound {
				w.WriteHeader(http.StatusNotFound)
			} else {
				results.InternalError(err, w)
			}

			return
		}

		w.WriteHeader(http.StatusOK)

		serverlog.Info(appID, LOG_NAME, "REMOVE FILE")
	})

	//Action para realizar o download do arquivo identificado pelo ID informado
	get.HandleFunc("/files/{id}", func(w http.ResponseWriter, req *http.Request) {
		log.Println(LOG_NAME, "GET ", req.URL.RequestURI())

		var (
			vars map[string]string
			id   string
			err  error
			file *model.File
			fs   model.VFStorage
		)

		vars = mux.Vars(req)
		id = vars["id"]
		fs, err = getDefaultStorage(getAppID(req))

		if err != nil {
			results.InternalError(err, w)
			return
		}

		file, err = fs.Find(id)

		if err != nil {

			//O erro retornado pode apontar que o arquivo não existe para o usuário
			if err == model.ErrFileNotFound {
				results.NotFound(w)
				return
			}

			results.InternalError(err, w)
			return
		}

		//Inclui headers com detalhes sobre o arquivo
		w.Header().Add(X_FILE_ID_HEADER, file.ID)
		w.Header().Add(X_FILE_NAME_HEADER, file.Name)

		results.File(file.Stream, file.MimeType, w)

		serverlog.Info(file.App, LOG_NAME, "GET FILE")
	})

	//Action para recuperar situação das estatísticas de armazenamento da aplicação
	get.HandleFunc("/stats/stats.json", func(w http.ResponseWriter, req *http.Request) {
		log.Println(LOG_NAME, "GET ", req.URL.RequestURI())

		appID := getAppID(req)
		fs, err := getDefaultStorage(appID)

		if err != nil {
			results.InternalError(err, w)
			return
		}

		stats, err := fs.Stats()

		if err != nil {
			results.InternalError(err, w)
			return
		}

		if stats == nil {
			w.WriteHeader(http.StatusNotFound)
			return
		}

		results.Json(stats, w)

		serverlog.Info(appID, LOG_NAME, "GET JSON STATS")
	})
}