示例#1
0
func EnvironmentGetAll(ctx *echo.Context) error {
	interactor := ctx.Get("EnvironmentInteractor").(*usecases.EnvironmentInteractor)

	result := interactor.List()

	return ctx.JSON(http.StatusOK, result)
}
示例#2
0
// FileServerHandler function
func FileServerHandler(c *echo.Context) error {
	fileType := mime.TypeByExtension(filepath.Ext(filepath.Base(c.Request().URL.String())))
	log.Println(c.Request().URL.String()[1:])
	c.Response().Header().Set("Content-Type", fileType)
	io.Copy(c.Response(), bytes.NewReader(staticFiles.Get(c.Request().URL.String()[1:])))
	return nil
}
示例#3
0
/**
 * @api {get} /topics Get a list of topics
 * @apiName GetTopics
 * @apiGroup Topics
 *
 * @apiParam {Number} [limit=10] The maximum number of items to return
 * @apiParam {Number} [offset=0] The offset relative to the number of items (not page number)
 */
func (tc *TopicsController) Index(c *echo.Context) error {
	resp := response.New(c)
	defer resp.Render()

	// Defaults
	var limit int64 = 10
	var offset int64 = 0

	// Getting limit
	limitInt, err := strconv.ParseInt(c.Query("limit"), 10, 64)
	if err == nil {
		limit = limitInt
	}

	// Getting offset
	offsetInt, err := strconv.ParseInt(c.Query("offset"), 10, 64)
	if err == nil {
		offset = offsetInt
	}

	// Fetching models
	res, err := models.AllTopics(limit, offset)
	if err != nil {
		resp.SetResponse(http.StatusInternalServerError, nil)
		return nil
	}

	resp.SetResponse(http.StatusOK, res)
	return nil
}
示例#4
0
// Make an application unusable
func UnpublishApplication(c *echo.Context) error {
	user := c.Get("user").(*users.User)

	appId := c.Param("app_id")
	if len(appId) < 1 {
		return c.JSON(http.StatusBadRequest, hash{
			"error": [1]hash{
				hash{
					"detail": "App id must be specified",
				},
			},
		})
	}

	err := apps.UnpublishApp(user, appId)
	if err == apps.UnpublishFailed {
		return c.JSON(http.StatusInternalServerError, hash{
			"error": [1]hash{
				hash{
					"detail": err.Error(),
				},
			},
		})
	}

	return c.JSON(http.StatusOK, hash{
		"meta": hash{},
	})
}
示例#5
0
func renderInstall(ctx echo.Context, filename string, data map[string]interface{}) error {
	objLog := getLogger(ctx)

	if data == nil {
		data = make(map[string]interface{})
	}

	filename = config.TemplateDir + filename

	requestURI := ctx.Request().URI()
	tpl, err := template.ParseFiles(filename)
	if err != nil {
		objLog.Errorf("解析模板出错(ParseFiles):[%q] %s\n", requestURI, err)
		return err
	}

	buf := new(bytes.Buffer)
	err = tpl.Execute(buf, data)
	if err != nil {
		objLog.Errorf("执行模板出错(Execute):[%q] %s\n", requestURI, err)
		return err
	}

	return ctx.HTML(http.StatusOK, buf.String())
}
示例#6
0
文件: user.go 项目: jacoelho/lodestar
func UserList(ctx *echo.Context) error {
	interactor := ctx.Get("UserInteractor").(*usecases.UserInteractor)

	result := interactor.List()

	return ctx.JSON(http.StatusOK, result)
}
示例#7
0
文件: handlers.go 项目: cedmundo/site
// ArchiveView shows a list of posts arranged by its date
func ArchiveView(c *echo.Context) error {
	id := c.Param("id")
	var err error

	// Get archive data
	var archive models.Archive
	err = database.Current.Get(&archive, database.Queries.ArchiveBySignature, id)
	if err != nil {
		log.Println("Cannot get archive by signature", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	// Get related posts
	var posts []models.AuthoredPost
	err = database.Current.Select(&posts, database.Queries.ArchiveAuthoredPosts, id)
	if err != nil {
		log.Println("Cannot select posts", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	// Create our render context and fill base data
	ac := archiveContext{
		Archive:      archive,
		RelatedPosts: posts,
	}

	err = fillBlogContext(c, &ac.blogContext)
	if err != nil {
		log.Println("Cannot fill blog context", err)
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	return c.Render(200, "archive", ac)
}
示例#8
0
func MakeCookie(context echo.Context, name string, value string) {
	cookie := new(echo.Cookie)
	cookie.SetName(name)
	cookie.SetValue(value)
	cookie.SetExpires(time.Now().Add(24 * 365 * time.Hour)) // Make the cookie good for a year
	context.SetCookie(cookie)
}
示例#9
0
func welcome(c *echo.Context) error {
	type User struct {
		Name string
		Age  int8
	}
	return c.Render(http.StatusOK, "welcome", User{Name: "schaffer", Age: 23})
}
示例#10
0
文件: api.go 项目: flike/kingshard
//get nodes status
func (s *ApiServer) GetNodesStatus(c echo.Context) error {
	var masterStatus, slaveStatus DBStatus

	dbStatus := make([]DBStatus, 0, 1)
	nodes := s.proxy.GetAllNodes()

	for nodeName, node := range nodes {
		//get master status
		masterStatus.Node = nodeName
		masterStatus.Address = node.Master.Addr()
		masterStatus.Type = "master"
		masterStatus.Status = node.Master.State()
		masterStatus.LastPing = fmt.Sprintf("%v", time.Unix(node.Master.GetLastPing(), 0))
		masterStatus.MaxConn = node.Cfg.MaxConnNum
		masterStatus.IdleConn = node.Master.IdleConnCount()
		dbStatus = append(dbStatus, masterStatus)

		//get slaves status
		for _, slave := range node.Slave {
			slaveStatus.Node = nodeName
			slaveStatus.Address = slave.Addr()
			slaveStatus.Type = "slave"
			slaveStatus.Status = slave.State()
			slaveStatus.LastPing = fmt.Sprintf("%v", time.Unix(slave.GetLastPing(), 0))
			slaveStatus.MaxConn = node.Cfg.MaxConnNum
			slaveStatus.IdleConn = slave.IdleConnCount()
			dbStatus = append(dbStatus, slaveStatus)
		}
	}
	return c.JSON(http.StatusOK, dbStatus)
}
示例#11
0
// Retrieve writes profile public information, if requested id is the same as the
// session, then full data is written.
func Retrieve(c *echo.Context) (int, interface{}) {
	reqid, _ := strconv.ParseInt(c.Param("id"), 10, 64)
	attid, _ := c.Get("digitsID").(int64)

	if reqid == attid {
		// Serve private profile
		var profile models.Profile

		log.Printf("Awaiting for [Profile = %d] fetch", reqid)
		err := mangos.FindOne(collection, bson.M{"_id": reqid}, &profile)
		if err != nil {
			log.Printf("Cannot retrieve [Profile = %d]: %s", reqid, err)
			return msg.InternalError(err)
		}

		log.Printf("Served profile ->\n%s", msg.Detail(profile))
		return msg.Ok(profile)
	}

	// Serve public profile
	var public models.PublicProfile
	log.Printf("Awaiting for [PublicProfile = %d] fetch", reqid)
	err := mangos.FindOne(collection, bson.M{"_id": reqid}, &public)
	if err != nil {
		log.Printf("Cannot retrieve [PublicProfile = %d]: %s", reqid, err)
		return msg.InternalError(err)
	}

	log.Printf("Served PublicProfile ->\n%s", msg.Detail(public))
	return msg.Ok(public)
}
示例#12
0
文件: api.go 项目: flike/kingshard
func (s *ApiServer) SaveProxyConfig(c echo.Context) error {
	err := s.proxy.SaveProxyConfig()
	if err != nil {
		return err
	}
	return c.JSON(http.StatusOK, "ok")
}
示例#13
0
文件: api.go 项目: flike/kingshard
func (s *ApiServer) ChangeMasterStatus(c echo.Context) error {
	args := struct {
		Opt  string `json:"opt"`
		Node string `json:"node"`
		Addr string `json:"addr"`
	}{}

	err := c.Bind(&args)
	if err != nil {
		return err
	}

	args.Opt = strings.ToLower(args.Opt)
	if args.Opt != "up" && args.Opt != "down" {
		return errors.New("opt only can be up or down")
	}
	if args.Opt == "down" {
		err = s.proxy.DownMaster(args.Node, args.Addr)
	} else {
		err = s.proxy.UpMaster(args.Node, args.Addr)
	}
	if err != nil {
		return err
	}
	return c.JSON(http.StatusOK, "ok")
}
示例#14
0
func GetDownloadToken(c *echo.Context) error {
	filename := c.Query("filename")
	if len(filename) == 0 {
		return c.JSON(
			http.StatusBadRequest,
			hash{
				"error": "filename not specified",
			},
		)
	}

	accessToken, fail := oauth2.GetAccessToken(c.Request())
	if fail != nil {
		return oauthError(c, fail)
	}

	user := c.Get("user").(*users.User)
	token, err := createDownloadToken(user, accessToken, filename)
	if err != nil {
		return err
	}
	return c.JSON(
		http.StatusOK,
		hash{
			"token": token,
		},
	)
}
示例#15
0
文件: groups.go 项目: cedmundo/hablo
// Create inserts a new group into database
func Create(c *echo.Context) (int, interface{}) {
	digitsID, ok := c.Get("digitsID").(int64)
	if !ok {
		return msg.Forbidden("session required")
	}

	// Bind request body with group
	var group models.Group
	err := c.Bind(&group)

	// Validate group
	err = validator.Validate(group)
	if err != nil {
		return msg.BadRequest(err)
	}

	// Set values
	group.ID = bson.NewObjectId()
	group.Admins = []int64{digitsID}
	group.Creator = digitsID
	group.Members = []int64{digitsID}

	// Create group
	err = mangos.Insert(constants.CGroups, group)
	if err != nil {
		return msg.InternalError(err)
	}

	return msg.Ok(group)
}
示例#16
0
文件: gothic.go 项目: laicosly/goth
func OauthResponse(c *echo.Context) (goth.Session, *goth.User, error) {

	//println("gothic.OauthResponse")
	platform, err := getPlatform(c)
	if err != nil {
		return nil, nil, err
	}
	req := c.Request()
	//println("gothic.getSession")
	sess, err := getSession(platform, req)
	if err != nil {
		return nil, nil, err
	}
	//println("gothic.Authorize")
	_, err = sess.Authorize(platform, req.URL.Query())
	if err != nil {
		return sess, nil, err
	}
	//println("gothic.OauthResponse.Authorize response", authorized)

	user, err := platform.FetchUser(sess)
	if err != nil {
		return nil, nil, err
	}
	return sess, user, nil
}
示例#17
0
文件: groups.go 项目: cedmundo/hablo
// Retrieve writes the requested group from database
func Retrieve(c *echo.Context) (int, interface{}) {
	digitsID, ok := c.Get("digitsID").(int64)
	if !ok {
		return msg.Forbidden("session required")
	}

	// Get group id and convert it from string to objectid
	rawGID := c.Param("gid")
	if !bson.IsObjectIdHex(rawGID) {
		return msg.BadRequest("bad id: not a ObjectId")
	}

	// find the group
	groupID := bson.ObjectIdHex(rawGID)
	var group models.Group
	err := mangos.FindOne(constants.CGroups, bson.M{"_id": groupID}, &group)
	if err != nil {
		return msg.InternalError(err)
	}

	// check if user is member (is not part of the query because we need to light bson query)
	for _, member := range group.Members {
		if member == digitsID {
			return msg.Ok(group)
		}
	}

	return msg.Forbidden("you must be part of the group")
}
示例#18
0
func PublishApp(c *echo.Context) error {
	body, err := ioutil.ReadAll(c.Request().Body)
	if err != nil {
		log.Error(err)
		return reterr(err, "", c)
	}
	var all struct {
		Data struct {
			Attributes struct {
				Alias          string `json:"alias"`
				CollectionName string `json:"collection-name"`
				DisplayName    string `json:"display-name"`
				FilePath       string `json:"file-path"`
				Path           string `json:"path"`
			}
			Type string `json:"type"`
		} `json:"data"`
	}
	err = json.Unmarshal(body, &all)
	if err != nil {
		log.Error(err)
		return reterr(err, "", c)
	}

	username, pwd, _ := c.Request().BasicAuth()
	utils.ExecuteCommandAsAdmin("C:\\Windows\\System32\\WindowsPowershell\\v1.0\\powershell.exe Import-module RemoteDesktop; New-RDRemoteApp -CollectionName "+all.Data.Attributes.CollectionName+" -DisplayName "+all.Data.Attributes.DisplayName+" -FilePath '"+all.Data.Attributes.Path+"'", username, pwd, domain)
	return checkIfPublishSucceeded(c, all.Data.Attributes.DisplayName)
}
示例#19
0
func List(c *echo.Context) error {

	user := c.Get("user").(*users.User)

	winUser, err := user.WindowsCredentials()
	if err != nil {
		return err
	}

	sessionList, err := sessions.GetAll(winUser.Sam)

	if err != nil {
		log.Error(err)
		return utils.JSON(c, http.StatusInternalServerError, hash{
			"error": [1]hash{
				hash{
					"detail": err.Error(),
				},
			},
		})
	}

	var response = make([]hash, len(sessionList))
	for i, val := range sessionList {
		res := hash{
			"id":         val.Id,
			"type":       "session",
			"attributes": val,
		}
		response[i] = res
	}

	return c.JSON(http.StatusOK, hash{"data": response})
}
示例#20
0
文件: http.go 项目: chop-dbhi/scds
func addSubscribersHandler(c echo.Context) error {
	cfg := c.Get("config").(*Config)

	var (
		err    error
		emails []string
	)

	if err = c.Bind(&emails); err != nil {
		return c.JSON(StatusUnprocessableEntity, map[string]interface{}{
			"message": "problem decoding request body",
			"error":   err,
		})
	}

	subs, err := SubscribeEmail(cfg, emails...)

	if err != nil {
		return c.JSON(StatusUnprocessableEntity, map[string]interface{}{
			"message": "problem subscribing emails",
			"error":   err,
		})
	}

	return c.JSON(http.StatusOK, map[string]interface{}{
		"subscribed": len(subs),
	})
}
示例#21
0
文件: handlers.go 项目: cedmundo/site
// fillBlogContext dumps into a blog context default query values.
func fillBlogContext(c *echo.Context, bc *blogContext) error {
	var err error

	// Query the categories
	err = database.Current.Select(&bc.Categories, database.Queries.Categories)
	if err != nil {
		return err
	}

	// Query the archive
	err = database.Current.Select(&bc.Archives, database.Queries.Archives)
	if err != nil {
		return err
	}

	bc.Info = config.BlogInfo

	errparam := c.Query("error")
	if errparam != "" {
		bc.HasError = true
		bc.ErrorText = errparam
	}

	msgparam := c.Query("msg")
	if msgparam != "" {
		bc.HasMsg = true
		bc.MsgText = msgparam
	}
	return nil
}
示例#22
0
func getGroups(ctx *echo.Context) error {
	list, err := allGroups(dbFromContext(ctx))
	if err != nil {
		return err
	}
	return ctx.JSON(200, list)
}
// echov2-standard
func echov2Handler(c echov2.Context) error {
	if sleepTime > 0 {
		time.Sleep(sleepTimeDuration)
	}
	c.Response().Write(message)
	return nil
}
示例#24
0
func getGroupHandler(ctx *echo.Context) error {
	g, err := getGroup(dbFromContext(ctx), ctx.Param("id"))
	if err != nil {
		return err
	}
	return ctx.JSON(200, g)
}
示例#25
0
// Add a new log entry to the database
func Add(c *echo.Context) error {
	history := histories.History{}

	err := utils.ParseJSONBody(c, &history)
	if err != nil {
		return err
	}

	if history.UserId == "" || history.ConnectionId == "" || history.StartDate == "" || history.EndDate == "" {
		log.Error("Missing one or several parameters to create entry")
		return c.JSON(http.StatusBadRequest, hash{
			"error": [1]hash{
				hash{
					"detail": "Missing parameters",
				},
			},
		})
	}

	err = utils.ParseJSONBody(c, &history)
	newHistory, err := histories.CreateHistory(
		history.UserId,
		history.ConnectionId,
		history.StartDate,
		history.EndDate,
	)

	if err != nil {
		return err
	}

	return utils.JSON(c, http.StatusCreated, newHistory)
}
func (h *handler) handleUploadTarFunc(c echo.Context) error {
	req := c.Request()
	basePath := req.Header().Get(shared.BASE_PATH_HTTP_HEADER_NAME)
	if strings.TrimSpace(basePath) == "" {
		return fmt.Errorf("Request does not contain header '%s'", shared.BASE_PATH_HTTP_HEADER_NAME)
	}
	isDirVal := req.Header().Get(shared.IS_DIR_HTTP_HEADER_NAME)
	if strings.TrimSpace(isDirVal) == "" {
		return fmt.Errorf("Request does not contain header '%s'", shared.IS_DIR_HTTP_HEADER_NAME)
	}
	isDir := strings.TrimSpace(isDirVal) == "1"

	if isDir {
		//TODO: Is permission fine?
		if err := os.MkdirAll(basePath, 0755); err != nil {
			return fmt.Errorf("Unable to create base path %s, error: %s", basePath, err.Error())
		}
	}

	if isDir {
		h.logger.Infof("Now starting to receive dir '%s'", basePath)
		tarReceiver := tar_io.Factories.TarReceiver.Dir(basePath)
		return tar_io.SaveTarToReceiver(req.Body(), tarReceiver)
	} else {
		h.logger.Infof("Now starting to receive file '%s'", basePath)
		tarReceiver := tar_io.Factories.TarReceiver.File(basePath)
		return tar_io.SaveTarToReceiver(req.Body(), tarReceiver)
	}
}
示例#27
0
/**
 * @api {put} /topics/{id} Updates a topic
 * @apiName UpdateTopic
 * @apiGroup Topics
 *
 * @apiParam {Number} id The id of the topic to update
 * @apiParam {String} [name] The new name of the topic
 */
func (tc *TopicsController) Update(c *echo.Context) error {
	resp := response.New(c)
	defer resp.Render()

	// Getting params
	id, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		resp.SetResponse(http.StatusBadRequest, nil)
		return nil
	}

	// Loading the topic
	topic := new(models.Topic)
	err = topic.Load(id)
	if err != nil {
		resp.SetResponse(http.StatusNotFound, nil)
		return nil
	}

	name := c.Form("name")
	if name != "" {
		topic.Name = name
	}

	err = topic.Update()
	if err != nil {
		resp.SetResponse(http.StatusInternalServerError, nil)
		return nil
	}

	resp.SetResponse(http.StatusOK, topic)
	return nil
}
示例#28
0
文件: groups.go 项目: cedmundo/hablo
// Delete removes a group from database
func Delete(c *echo.Context) (int, interface{}) {
	digitsID, ok := c.Get("digitsID").(int64)
	if !ok {
		return msg.Forbidden("session required")
	}

	// Get group id and convert from string to objectId
	rawGID := c.Param("gid")
	if !bson.IsObjectIdHex(rawGID) {
		return msg.BadRequest("bad id: not a ObjectId")
	}

	// find the group
	groupID := bson.ObjectIdHex(rawGID)
	err := mangos.Delete(constants.CGroups, bson.M{
		"$and": []bson.M{
			bson.M{"_id": groupID},
			bson.M{"admins": digitsID},
		},
	})
	if err != nil {
		return msg.InternalError(err)
	}

	return msg.Ok("deleted")
}
示例#29
0
// Home shows the resumes home page.
//
//		Method           GET
//
//		Route            /resume/
//
//		Restrictions     Yes
//
// 		Template         resume/home.html
func Home(ctx *echo.Context) error {
	user := ctx.Get("User").(*models.Person)
	if res, err := query.GetAllPersonResumes(user); err == nil {
		utils.SetData(ctx, "resumes", res)
	}
	return ctx.Render(http.StatusOK, tmpl.ResumeHomeTpl, utils.GetData(ctx))
}
示例#30
0
文件: app.go 项目: exu/go-workshops
func apiHandler(c *echo.Context) error {
	i := 0
	response := c.Response()

	// ustawiamy header na event-stream rozpoznawalny przez przeglądarkę
	response.Header().Set(echo.ContentType, "text/event-stream")
	response.WriteHeader(http.StatusOK) // 200

	for {
		location := locations[i]
		response.Write([]byte("data: "))

		if err := json.NewEncoder(response).Encode(location); err != nil {
			return err
		}

		response.Write([]byte("\n\n"))
		response.Flush()
		time.Sleep(100 * time.Millisecond)

		i++
		if i >= len(locations) {
			i = 0
		}

	}

	return nil
}