Пример #1
0
// 最新开源项目(TODO:暂时打乱,避免每次一样)
// uri: /projects/recent.json
func RecentProjectHandler(rw http.ResponseWriter, req *http.Request) {
	var (
		limit = 10
		err   error
	)
	limitStr := req.FormValue("limit")
	if limitStr != "" {
		limit, err = strconv.Atoi(limitStr)
		if err != nil {
			fmt.Fprint(rw, `{"ok": 0, "error":"limit is not number"}`)
			return
		}
	}

	recentProjects := service.FindProjects("0", "100")
	start, end := 0, len(recentProjects)
	if n := end - limit; n > 0 {
		start = rand.Intn(n)
		end = start + limit
	}

	buf, err := json.Marshal(recentProjects[start:end])
	if err != nil {
		logger.Errorln("[RecentProjectHandler] json.marshal error:", err)
		fmt.Fprint(rw, `{"ok": 0, "error":"解析json出错"}`)
		return
	}
	fmt.Fprint(rw, `{"ok": 1, "data":`+string(buf)+`}`)
}
Пример #2
0
// 开源项目列表页
// uri: /projects
func ProjectsHandler(rw http.ResponseWriter, req *http.Request) {
	limit := 20

	lastId := req.FormValue("lastid")
	if lastId == "" {
		lastId = "0"
	}

	projects := service.FindProjects(lastId, "25")
	if projects == nil {
		// TODO:服务暂时不可用?
	}

	num := len(projects)
	if num == 0 {
		if lastId == "0" {
			util.Redirect(rw, req, "/")
		} else {
			util.Redirect(rw, req, "/projects")
		}

		return
	}

	var (
		hasPrev, hasNext bool
		prevId, nextId   int
	)

	if lastId != "0" {
		prevId, _ = strconv.Atoi(lastId)

		// 避免因为项目下线,导致判断错误(所以 > 5)
		if prevId-projects[0].Id > 5 {
			hasPrev = false
		} else {
			prevId += limit
			hasPrev = true
		}
	}

	if num > limit {
		hasNext = true
		projects = projects[:limit]
		nextId = projects[limit-1].Id
	} else {
		nextId = projects[num-1].Id
	}

	pageInfo := map[string]interface{}{
		"has_prev": hasPrev,
		"prev_id":  prevId,
		"has_next": hasNext,
		"next_id":  nextId,
	}

	// 获取当前用户喜欢对象信息
	user, ok := filter.CurrentUser(req)
	var likeFlags map[int]int
	if ok {
		uid := user["uid"].(int)
		likeFlags, _ = service.FindUserLikeObjects(uid, model.TYPE_PROJECT, projects[0].Id, nextId)
	}

	req.Form.Set(filter.CONTENT_TPL_KEY, "/template/projects/list.html")
	// 设置模板数据
	filter.SetData(req, map[string]interface{}{"projects": projects, "activeProjects": "active", "page": pageInfo, "likeflags": likeFlags})
}