Esempio n. 1
0
func renderTemplate(webContext *web.Context, template string, action string, context interface{}, statusCode int) {
	webContext.WriteHeader(statusCode)
	err := templates[template].ExecuteTemplate(webContext, action+".html", context)

	if err != nil {
		log.Println("[ERROR] renderTemplate: ", err)
		webContext.Abort(500, "Unable to process request.")
	}
}
Esempio n. 2
0
func S3GetHandler(ctx *web.Context, key string) (ret string) {
	val := FakeS3[key]
	if val == "" {
		ctx.Abort(404, "Not Found")
		return
	} else if val == "FAIL" {
		ctx.Redirect(301, "htttttttp://idon'twork")
		return
	} else {
		return val
	}
}
Esempio n. 3
0
// Upsert an item in the datastore.
func upsertItem(ctx *web.Context, key string) string {
	value := ctx.Params["value"]
	if value == "" {
		ctx.Abort(400, "Item creation is missing a value")
		return ""
	}

	// insert the item
	item := datastore.NewItem(key, value)
	ds.InsertItem(item)

	return "created " + key
}
Esempio n. 4
0
// A Flatpage view.  Attach it via web.Get wherever you want flatpages to be available
func Flatpage(ctx *web.Context, url string) string {
	p := GetPage(url)
	if p == nil {
		ctx.Abort(404, "Page not found")
		return ""
	}

	return template.Render("base.mandira", M{
		"body":        p.ContentRendered,
		"title":       "jmoiron.net",
		"description": "Blog and assorted media from Jason Moiron.",
	})
}
Esempio n. 5
0
// documentStream handles websocket requests from the client for a particular document
func documentStream(ctx *web.Context, documentId string) {
	w := ctx.ResponseWriter
	r := ctx.Request
	if r.Header.Get("Origin") != "http://"+r.Host {
		ctx.Abort(403, "Origin not allowed")
		// http.Error(w, "Origin not allowed", 403)
		return
	}
	ws, err := websocket.Upgrade(w, r.Header, nil, 1024, 1024)
	if _, ok := err.(websocket.HandshakeError); ok {
		ctx.Abort(400, "Not a websocket handshake")
		return
	} else if err != nil {
		log.Println(err)
		return
	}
	redis_conn, _ := hub.GetRedis()
	defer redis_conn.Close()
	s, err := redis.String(redis_conn.Do("GET", documentId))
	//make new document at that stringId
	if err != nil {
		doc := document.NewDoc(documentId)
		document_hubs[doc.Name] = hub.DocumentHub{
			Document:    doc,
			Broadcast:   make(chan hub.Message),
			Register:    make(chan *hub.DocumentConnection),
			Unregister:  make(chan *hub.DocumentConnection),
			Connections: make(map[*hub.DocumentConnection]bool),
		}
		h := document_hubs[doc.Name]
		go h.Run()
		json_bytes, _ := json.Marshal(doc)
		redis_conn.Do("SET", documentId, string(json_bytes))
		c := &hub.DocumentConnection{Send: make(chan hub.Message, 256), Ws: ws, H: document_hubs[doc.Name]}
		document_hubs[doc.Name].Register <- c
		mainHub.Broadcast <- json_bytes
		go c.WritePump()
		c.ReadPump()
	} else {
		var doc document.Document
		fmt.Println(s)
		err := json.Unmarshal([]byte(s), &doc)
		if err != nil {
			fmt.Println("Error:", err, s)
		}
		c := &hub.DocumentConnection{Send: make(chan hub.Message, 256), Ws: ws, H: document_hubs[doc.Name]}
		document_hubs[doc.Name].Register <- c
		go c.WritePump()
		c.ReadPump()
	}
}
Esempio n. 6
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()
	}
}
Esempio n. 7
0
File: app.go Progetto: inhies/monet
func blogDetail(ctx *web.Context, slug string) string {
	var post = new(Post)
	err := db.Find(post, M{"slug": slug}).One(&post)
	if err != nil {
		fmt.Println(err)
		ctx.Abort(404, "Page not found")
		return ""
	}

	return template.Render("base.mandira", M{
		"body":        RenderPost(post),
		"title":       post.Title,
		"description": post.Summary})
}
Esempio n. 8
0
// A Flatpage view.  Attach it via web.Get wherever you want flatpages to be available
func Flatpage(ctx *web.Context, url string) string {
	p := GetPage(url)
	fmt.Printf("Got page %v for url %s\n", p, url)
	if p == nil {
		ctx.Abort(404, "Page not found")
		return ""
	}

	return template.Render("base.mandira", M{
		"body":        p.ContentRendered,
		"title":       "Jamil Seaidoun",
		"description": "Blog and assorted media from Jamil Seaidoun.",
	})
}
Esempio n. 9
0
/**
 * Handles request for section
 */
func handlePaginatedSection(ctx *web.Context, section string, page string) string {
	config, err := getConfig()
	if err != nil {
		ctx.Abort(500, "Configuration error.")
		return ""
	}
	tpl := pongo.Must(pongo.FromFile(config.TemplateFolder+"/template.html", nil))
	var content, output string
	p, _ := strconv.Atoi(page)
	output, err = getAbstracts(section, p, &config)
	if err != nil {
		ctx.Abort(404, "Page not found. Could not load abstracts")
		return ""
	}
	content = string(blackfriday.MarkdownCommon([]byte(output)))
	menu, err := getMenu(&config)
	if err != nil {
		ctx.Abort(501, "Could not load menu")
		return ""
	}
	var response *string
	response, err = tpl.Execute(&pongo.Context{"content": content, "menu": menu,
		"currentMenu": menu.GetCurrent(section)})
	if err != nil {
		ctx.Abort(501, "")
		return err.Error()
	}
	return *response
}
Esempio n. 10
0
// Wrapper for handling paginated section when no section is given
func handleSection(ctx *web.Context, section string) string {
	if len(section) == 0 {
		config, err := getConfig()
		if err != nil {
			ctx.Abort(500, "Configuration error.")
			return ""
		}
		menu, err := getMenu(&config)
		if err != nil {
			ctx.Abort(501, "Could not load menu")
			return ""
		}
		return handlePaginatedSection(ctx, menu[0].Section, "1")
	}
	return handlePaginatedSection(ctx, section, "1")
}
Esempio n. 11
0
// Returns a key or abort with an error if it doesn't exist or the item
// has gone mainstream.
func getItem(ctx *web.Context, key string) string {
	item, err := ds.GetItem(key)
	if err != nil {
		var errorStatus int
		if err.Error() == datastore.ACCESS_MISSING {
			errorStatus = 404
		} else {
			errorStatus = 403
		}

		ctx.Abort(errorStatus, err.Error())
		return ""
	}

	return item.Value
}
Esempio n. 12
0
func (c *Controller) PublishPost(ctx *web.Context) {
	if !c.sessionManager.LoggedIn(ctx) {
		ctx.Redirect(303, "/login")
		return
	}

	file, head, err := ctx.Request.FormFile("publishFile")
	if err != nil {
		ctx.Abort(405, "error, post without a file")
		return
	}
	saveFile, err := os.Create("articles/" + head.Filename)
	defer saveFile.Close()
	io.Copy(saveFile, file)
	file.Close()
	ctx.Redirect(303, "/publish")
}
Esempio n. 13
0
func deleteDocument(ctx *web.Context, documentId string) {
	redis_conn, _ := hub.GetRedis()
	defer redis_conn.Close()

	//make new document at that stringId
	if _, ok := document_hubs[documentId]; ok {
		h := document_hubs[documentId]
		var buf bytes.Buffer
		doc := document.Document{Name: h.Document.Name, Title: h.Document.Title, Version: h.Document.Version}
		redis_conn.Do("DEL", documentId)
		json_bytes, _ := json.Marshal(doc)
		h.Broadcast <- hub.Message{M: json_bytes}
		buf.Write(json_bytes)
		io.Copy(ctx, &buf)
	} else {
		ctx.Abort(404, "Document does not exist")
		return
	}
}
Esempio n. 14
0
// serverWs handles websocket requests from the client.
func serveWs(ctx *web.Context) {
	w := ctx.ResponseWriter
	r := ctx.Request
	if r.Header.Get("Origin") != "http://"+r.Host {
		ctx.Abort(403, "Origin not allowed")
		// http.Error(w, "Origin not allowed", 403)
		return
	}
	ws, err := websocket.Upgrade(w, r.Header, nil, 1024, 1024)
	if _, ok := err.(websocket.HandshakeError); ok {
		ctx.Abort(400, "Not a websocket handshake")
		return
	} else if err != nil {
		log.Println(err)
		return
	}
	c := &hub.Connection{Send: make(chan []byte, 256), Ws: ws, H: mainHub}
	mainHub.Register <- c
	go c.WritePump()
	c.ReadPump()
}
Esempio n. 15
0
File: api.go Progetto: nfleet/via
func (server *Server) PostPaths(ctx *web.Context) string {
	var input struct {
		Paths        []geotypes.NodeEdge
		Country      string
		SpeedProfile int
	}

	var (
		computed []geotypes.Path
	)

	if err := json.NewDecoder(ctx.Request.Body).Decode(&input); err != nil {
		content, _ := ioutil.ReadAll(ctx.Request.Body)
		ctx.Abort(400, "Couldn't parse JSON: "+err.Error()+" in '"+string(content)+"'")
		return ""
	} else {
		var err error
		computed, err = server.Via.CalculatePaths(input.Paths, input.Country, input.SpeedProfile)
		if err != nil {
			ctx.Abort(422, "Couldn't resolve addresses: "+err.Error())
			return ""
		}
	}

	res, err := json.Marshal(computed)
	if err != nil {
		ctx.Abort(500, "Couldn't serialize paths: "+err.Error())
		return ""
	}

	ctx.Header().Set("Access-Control-Allow-Origin", "*")
	ctx.ContentType("application/json")
	return string(res)
}
Esempio n. 16
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()
	}
}
Esempio n. 17
0
func setDocumentTitle(ctx *web.Context, documentId string) {
	redis_conn, _ := hub.GetRedis()
	defer redis_conn.Close()

	//make new document at that stringId
	if _, ok := document_hubs[documentId]; ok {
		body, _ := ioutil.ReadAll(ctx.Request.Body)
		var ndoc document.Document
		json.Unmarshal(body, &ndoc)
		h := document_hubs[documentId]
		h.Document.Title = ndoc.Title
		var buf bytes.Buffer
		doc := document.Document{Name: h.Document.Name, Title: h.Document.Title, Version: h.Document.Version}
		h.Save(redis_conn)
		doc.ClientId = ndoc.ClientId
		json_bytes, _ := json.Marshal(doc)
		mainHub.Broadcast <- json_bytes
		buf.Write(json_bytes)
		io.Copy(ctx, &buf)
	} else {
		ctx.Abort(404, "Document does not exist")
		return
	}
}
Esempio n. 18
0
func APIErrorResponse(ctx *web.Context, message string, status int) {
	resp_text := APIResponse(ctx, map[string]interface{}{"error": message})
	ctx.Abort(status, resp_text)
}
Esempio n. 19
0
File: api.go Progetto: nfleet/via
// Starts a computation, validates the matrix in POST.
// If matrix data is missing, returns 400 Bad Request.
// If on the other hand matrix is data is not missing,
// but makes no sense, it returns 422 Unprocessable Entity.
func (server *Server) PostMatrix(ctx *web.Context) {
	defer runtime.GC()

	// Parse params
	var paramBlob struct {
		Matrix       []int   `json:"matrix"`
		Country      string  `json:"country"`
		SpeedProfile float64 `json:"speed_profile"`
	}
	if err := json.NewDecoder(ctx.Request.Body).Decode(&paramBlob); err != nil {
		ctx.Abort(400, err.Error())
		return
	}

	data := paramBlob.Matrix
	country := strings.ToLower(paramBlob.Country)
	sp := int(paramBlob.SpeedProfile)

	ok := len(data) > 0 && country != "" && sp > 0
	if ok {
		// Sanitize speed profile.
		if !contains(sp, allowedSpeeds) {
			msg := fmt.Sprintf("speed profile '%d' makes no sense, must be one of %s", sp, fmt.Sprint(allowedSpeeds))
			ctx.Abort(422, msg)
			return
		}
		// Sanitize country.
		if _, ok := server.AllowedCountries[country]; !ok {
			countries := ""
			for k := range server.AllowedCountries {
				countries += k + " "
			}
			ctx.Abort(422, "country "+country+" not allowed, must be one of: "+countries)
			return
		}

		matrix, err := server.Via.ComputeMatrix(data, country, sp)
		if err != nil {
			viaErr.NewError(viaErr.ErrMatrixComputation, err.Error()).WriteTo(ctx.ResponseWriter)
			return
		}

		result := Result{
			Progress:     "complete",
			Matrix:       matrix,
			SpeedProfile: sp,
		}

		ctx.WriteHeader(200)
		ctx.ContentType("json")
		if err := json.NewEncoder(ctx.ResponseWriter).Encode(result); err != nil {
			viaErr.NewError(viaErr.ErrMatrixComputation, "Failed to encode results to response writer.").WriteTo(ctx.ResponseWriter)
			return
		}

	} else {
		body, _ := ioutil.ReadAll(ctx.Request.Body)
		ctx.Abort(400, "Missing or invalid matrix data, speed profile, or country. You sent: "+string(body))
		return
	}
}