Example #1
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()
	}
}