Пример #1
0
func api(ctx *web.Context, username string) string {
	user, err := getUser(username)
	ctx.SetHeader("Content-Type", "application/prs.kevinburke.snapchat-v1+json", true)
	if err != nil {
		checkError(err)
		ctx.NotFound("User not found")
		return ""
	}
	friends, err := getFriendsById(user.Id)
	checkError(err)
	var links Links
	var users []User
	users = append(users, *user)
	for i := 0; i < len(friends.Friends); i++ {
		friend := friends.Friends[i]
		link := Link{friend.UserId, friend.FriendId, friend.Index}
		links.Links = append(links.Links, link)
		user, err := getUserById(friend.UserId)
		checkError(err)
		users = append(users, *user)
	}
	response := Response{links.Links, users}
	bytes, err := json.Marshal(response)
	checkError(err)
	return string(bytes)
}
Пример #2
0
func (h *RestQueueHandler) Get(ctx *web.Context, val string) {
	queue := redisq.NewRedisQueue(h.redis, val)
	if !queue.Exists() {
		writeError(ctx, 404, QueueNotFound)
		return
	}
	if queue.Empty() {
		writeError(ctx, 400, EmptyQueue)
		return
	}
	mesg, err := queue.GetNoWait()
	if err != nil {
		writeError(ctx, 500, GetError)
		if Settings.Debug {
			debug := fmt.Sprintf("Debug: %s", err)
			ctx.WriteString(debug)
		}
		h.logger.Printf("Dequeue from <%s> Error:%s", val, err)
		return
	}
	resp, _ := json.Marshal(mesg)
	//mesg.(type) is iteface{}
	//resp.(type) is []byte

	ctx.SetHeader("Content-Type", "application/json; charset=UTF-8", true)
	ctx.WriteString(string(resp))

}
Пример #3
0
func vnstat(ctx *web.Context, iface string, debug string) string {
	app := "vnstat"

	arg0 := "-i"
	arg2 := "--xml"

	ctx.SetHeader("Content-Type", "application/json", true)

	rawxml := runcmd(app, arg0, iface, arg2)

	var q Vnstat
	xml.Unmarshal([]byte(rawxml), &q)

	var jsondata []byte
	var err error

	if debug == "debug" {
		jsondata, err = json.MarshalIndent(q, "", "  ")
	} else {
		jsondata, err = json.Marshal(q)
	}

	if err != nil {
		return "Error"
	}
	return string(jsondata)
}
Пример #4
0
func search(ctx *web.Context, collection string) {
	ctx.ContentType("json")
	ctx.SetHeader("Access-Control-Allow-Origin", "*", true)

	query := ctx.Params["query"]

	var limit, offset int64
	var err error

	if limit, err = strconv.ParseInt(ctx.Params["limit"], 10, 32); err != nil {
		limit = 10
	}
	if offset, err = strconv.ParseInt(ctx.Params["offset"], 10, 32); err != nil {
		offset = 0
	}

	results, err := c.Search(collection, query, int(limit), int(offset))

	buf := new(bytes.Buffer)
	encoder := json.NewEncoder(buf)

	if err != nil {
		encoder.Encode(err)
		ctx.WriteHeader(err.(*gorc.OrchestrateError).StatusCode)
	} else {
		encoder.Encode(results)
	}

	ctx.Write(buf.Bytes())
}
Пример #5
0
func players(ctx *web.Context) []byte {
	ctx.SetHeader("Content-Type", "application/json", true)
	players, err := arena.GetPlayers()
	checkError(err)
	jsonPlayers, err := json.Marshal(players)
	checkError(err)
	return jsonPlayers
}
Пример #6
0
func (h *RestQueueHandler) List(ctx *web.Context) {

	var keys []string
	keys, _ = h.redis.Keys("*")
	resp, _ := json.Marshal(keys)
	ctx.SetHeader("Content-Type", "application/json; charset=UTF-8", true)
	ctx.WriteString(string(resp))
}
Пример #7
0
func serveCaptchaAudio(ctx *web.Context, id string) {
	//tell the user's browser not to cache the audio file
	//(would cause old audio file to be used even if user has reloaded the CAPTCHA)
	ctx.SetHeader("Cache-Control", "no-cache", true)

	err := captcha.WriteAudio(ctx, id, "english")
	if err != nil {
		logger.Println("Error, could not write CAPTCHA audio")
		logger.Println(err.Error())
	}
}
Пример #8
0
func uploader(ctx *web.Context, key string) {
	updateRemoteAddr(ctx)

	if _, ok := uploadRequests[key]; ok {
		// key exists
		ctx.Forbidden()
		return
	}

	wait := make(chan string)

	defer delete(uploadRequests, key)
	uploadRequests[key] = uploadRequest{ctx.Request, wait}

	var result string
	select {
	case result = <-wait:
	case <-time.After(WAIT_CLIENT_TIMEOUT):
		result = "wait client timeout"
	}

	if result == "connected" {
		// wait actual result
		result = <-wait
	}

	var body string

	if xrw := ctx.Request.Header.Get("X-Requested-With"); xrw == "XMLHttpRequest" {
		body = "{\"result\": \"" + result + "\"}\n"

		ctx.SetHeader("Content-Type", "application/json", true)
	} else {
		tmpl, err := template.New("uploader").Parse(uploadTemplate)

		if err != nil {
			panic(err)
		}

		var buf bytes.Buffer
		tmpl.Execute(&buf, UploadTemplateValue{result})
		body = buf.String()
	}

	if result == "ok" {
		ctx.WriteString(body)
	} else {
		ctx.Abort(500, body)
		ctx.Request.Body.Close()
	}
}
Пример #9
0
func Options(ctx *web.Context, route string) string {
	ctx.SetHeader("Access-Control-Allow-Origin", "*", false)
	ctx.SetHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, If-None-Match", false)
	ctx.SetHeader("Access-control-Allow-Methods", "GET, PUT, POST, DELETE", false)
	ctx.ContentType("application/json")
	return "{}"
}
Пример #10
0
/*
	Serves a CAPTCHA image
	Parameters:
		ctx:	The context of the http request
		id:		The ID of the captcha to serve
*/
func serveCaptchaImage(ctx *web.Context, id string) {

	width, err := strconv.Atoi(ctx.Params["width"])
	if err != nil {
		logger.Printf("Error: could not parse captcha image width of '%v'\n%v\n", ctx.Params["width"], err.Error())
		width = captcha.StdWidth
	}

	height, err := strconv.Atoi(ctx.Params["height"])
	if err != nil {
		logger.Printf("Error: could not parse captcha image height of '%v'\n%v\n", ctx.Params["height"], err.Error())
		height = captcha.StdHeight
	}

	//tell the user's browser not to cache the image file
	ctx.SetHeader("Cache-Control", "no-cache", true)

	err = captcha.WriteImage(ctx, id, width, height)
	if err != nil {
		logger.Println("Error, could not write CAPTCHA image")
		logger.Println(err.Error())
	}
}
Пример #11
0
func downloader(ctx *web.Context, key string) {
	updateRemoteAddr(ctx)

	up, ok := uploadRequests[key]

	if !ok {
		ctx.NotFound("key doesn't exist")
		return
	}

	up.wait <- "connected"

	result := "ng"
	defer func() { up.wait <- result }()

	mr, err := up.request.MultipartReader()
	if err != nil {
		ctx.Abort(500, err.Error())
		return
	}

	p, err := mr.NextPart()
	if p.FormName() == "size" {
		fileSize, err := ioutil.ReadAll(p)
		if err == nil {
			fileSize, err := strconv.ParseInt(string(fileSize), 10, 64)
			if err == nil && fileSize >= 0 {
				ctx.SetHeader("Content-Length", strconv.FormatInt(fileSize, 10), true)
			}
		}
	}

	p, err = mr.NextPart()
	if err != nil {
		ctx.Abort(500, err.Error())
		return
	}
	if p.FormName() != "file" {
		ctx.Abort(500, "invalid POST (upload) request")
		return
	}

	if contentType := p.Header.Get("Content-Type"); contentType != "" {
		ctx.SetHeader("Content-Type", contentType, true)
	}

	ctx.SetHeader("Content-Disposition", "attachment; filename="+p.FileName(), true)

	_, err = io.Copy(ctx, p)

	if err == nil {
		result = "ok"
	} else {
		// XXX: may expose too many infomation (such as client IP address)
		//result = err.Error()
	}
}
Пример #12
0
func getPaste(ctx *web.Context, uri string) string {
	c, err := redis.Dial("tcp", "localhost:6379")
	if err != nil {
		Log(err)
		return mustache.Render("Cannot connect to DB \r\n")
	}
	defer c.Close()
	y := "PASTE_DOES_NOT_EXIST"
	if matched, _ := regexp.MatchString("[a-zA-Z0-9]+", uri); matched {
		y = "paste_" + uri
	}
	x, err := redis.String(c.Do("GET", y))
	ctx.SetHeader("Content-Type", "text/plain", true)
	ctx.SetHeader("X-Powered-By", "web.go", true)
	ctx.SetHeader("Connection", "close", true)
	return mustache.Render(x)
}
Пример #13
0
func APIResponse(ctx *web.Context, resp interface{}) string {
	resp_text, _ := json.Marshal(resp)
	ctx.SetHeader("Content-Type", "application/json", true)
	return string(resp_text[:])
}