Ejemplo n.º 1
0
//Handles file retrieval. It uses getURL to send a hash to the urlHandler, and listens on
//sendURL for the proper filename.
func getFile(ctx *web.Context, file string) string {
	dir := file[0:3]
	fname := file[3:]
	path := "files/" + dir + "/" + fname
	//Open the file
	f, err := os.Open(path)
	if err != nil {
		return "Error reading file!\n"
	}

	//Get MIME
	r, err := ioutil.ReadAll(f)
	if err != nil {
		return "Error reading file!\n"
	}
	mime := http.DetectContentType(r)

	_, err = f.Seek(0, 0)
	if err != nil {
		return "Error reading the file\n"
	}
	//This is weird - ServeContent supposedly handles MIME setting
	//But the Webgo content setter needs to be used too
	//In addition, ServeFile doesn't work, ServeContent has to be used
	ctx.ContentType(mime)
	http.ServeContent(ctx.ResponseWriter, ctx.Request, path, time.Now(), f)
	return ""
}
Ejemplo n.º 2
0
func fragmentShaderHandler(ctx *web.Context, path string) {
	file, err := os.Open(path)
	check(err)
	ctx.ContentType("x-shader/x-fragment")
	_, err = io.Copy(ctx, file)
	check(err)
}
Ejemplo n.º 3
0
Archivo: api.go Proyecto: 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)
}
Ejemplo n.º 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())
}
Ejemplo n.º 5
0
func getSong(ctx *web.Context, song string) string {
	//Open the file
	f, err := os.Open("static/queue/" + song)
	if err != nil {
		return "Error reading file!\n"
	}

	//Get MIME
	r, err := ioutil.ReadAll(f)
	if err != nil {
		return "Error reading file!\n"
	}
	mime := http.DetectContentType(r)

	_, err = f.Seek(0, 0)
	if err != nil {
		return "Error reading the file\n"
	}
	//This is weird - ServeContent supposedly handles MIME setting
	//But the Webgo content setter needs to be used too
	//In addition, ServeFile doesn't work, ServeContent has to be used
	ctx.ContentType(mime)
	http.ServeContent(ctx.ResponseWriter, ctx.Request, "static/queue/"+song, time.Now(), f)
	return ""
}
Ejemplo n.º 6
0
func gamePageHandler(ctx *web.Context) {
	gamePage, err := os.Open("index.html")
	check(err)
	ctx.ContentType("html")
	_, err = io.Copy(ctx, gamePage)
	check(err)
}
Ejemplo n.º 7
0
func getCover(ctx *web.Context, album string) string {
	dir := musicDir + "/" + album
	cover := "static/image/missing.png"
	if exists(dir + "/cover.jpg") {
		cover = dir + "/cover.jpg"
	} else if exists(dir + "/cover.png") {
		cover = dir + "/cover.png"
	}
	//Open the file
	f, err := os.Open(cover)
	if err != nil {
		return "Error reading file!\n"
	}

	//Get MIME
	r, err := ioutil.ReadAll(f)
	if err != nil {
		return "Error reading file!\n"
	}
	mime := http.DetectContentType(r)

	_, err = f.Seek(0, 0)
	if err != nil {
		return "Error reading the file\n"
	}
	//This is weird - ServeContent supposedly handles MIME setting
	//But the Webgo content setter needs to be used too
	//In addition, ServeFile doesn't work, ServeContent has to be used
	ctx.ContentType(mime)
	http.ServeContent(ctx.ResponseWriter, ctx.Request, cover, time.Now(), f)
	return ""
}
Ejemplo n.º 8
0
func pngHandler(ctx *web.Context, path string) {
	file, err := os.Open(path)
	check(err)
	ctx.ContentType("png")
	_, err = io.Copy(ctx, file)
	check(err)
}
Ejemplo n.º 9
0
Archivo: server.go Proyecto: nfleet/via
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 "{}"
}
Ejemplo n.º 10
0
func Sendstatic(ctx *web.Context, val string) {
	file, _err := ioutil.ReadFile("static/" + val)
	if _err != nil {
		return
	}
	filetype := strings.Split(val, ".")
	ctx.ContentType(filetype[len(filetype)-1])
	ctx.WriteString(string(file))
}
Ejemplo n.º 11
0
func (c StaticController) renderContent(ctx *web.Context, contentType, filepath string) {
	if file, err := os.Open(filepath); err != nil {
		w := ResponseWriter{ctx, "HTML"}
		w.SendError(err)
	} else {
		ctx.ContentType(contentType + "; charset=utf-8")
		reader := bufio.NewReader(file)
		io.Copy(ctx.ResponseWriter, reader)
	}
}
Ejemplo n.º 12
0
func hexagram(ctx *web.Context, num string) string {
	n, _ := strconv.Atoi(num)
	hexagram, found := iching.GetHexagramByNum(n)
	ctx.ContentType("json")

	if found {
		js, _ := json.Marshal(hexagram)
		return string(js)
	}

	return "Hexagram not found"
}
Ejemplo n.º 13
0
func reading(ctx *web.Context) string {
	ctx.Request.ParseForm()
	question := ctx.Request.Form.Get("question")
	ctx.ContentType("json")

	if question == "" {
		question = "No question provided"
	}

	reading := iching.GetReading(question)
	js, _ := json.Marshal(reading)

	return string(js)
}
Ejemplo n.º 14
0
func GetDeployments(ctx *web.Context) {
	fmt.Printf("************************************\n")
	deployments, err := LoadDeployments()
	if err != nil {
		fmt.Println(err)
		return
	}
	for _, deployment := range deployments {
		fmt.Printf(" Deployment %s ...\n", deployment.Name)
	}
	b, err := json.Marshal(deployments)
	if err != nil {
		fmt.Println("error:", err)
	}
	ctx.ContentType("json")
	ctx.Write(b)
}
Ejemplo n.º 15
0
// RenderDistributionImage renders the distribution image for the globe.
func (c PngController) RenderDistributionImage(ctx *web.Context, scale string) {
	intScale := c.convertScale(scale)

	if img, err := c.getBackgroundImage(intScale); err != nil {
		rw := ResponseWriter{ctx, "JSON"}
		rw.SendError(err)
	} else {
		distributions := c.database.GetDistributions()
		sort.Sort(DistributionSorter(distributions))

		for _, dist := range distributions {
			c.drawDistribution(img, float32(dist.Latitude), float32(dist.Longitude), float32(intScale)/float32(2), int(dist.ZipCodes))
		}

		ctx.ContentType("image/png")
		png.Encode(ctx.ResponseWriter, img)
	}
}
Ejemplo n.º 16
0
func generate(ctx *web.Context, val string) {
	ctx.ContentType("image/png")

	var width = 100
	var height = 100
	if w, ok := ctx.Params["w"]; ok {
		width, _ = strconv.Atoi(w)
	}
	if h, ok := ctx.Params["h"]; ok {
		height, _ = strconv.Atoi(h)
	}

	m := image.NewRGBA(image.Rect(0, 0, width, height))
	grey := color.RGBA{0, 0, 0, 50}
	draw.Draw(m, m.Bounds(), &image.Uniform{grey}, image.ZP, draw.Src)

	png.Encode(ctx, m)
}
Ejemplo n.º 17
0
// RenderImage renders the simple distribution image.
func (c PngController) RenderImage(ctx *web.Context, scale string) {
	intScale := c.convertScale(scale)

	img, err := c.getBackgroundImage(intScale)
	if err != nil {
		rw := ResponseWriter{ctx, "JSON"}
		rw.SendError(err)
		return
	}

	for _, cim := range c.database.CountryIndexMap {
		for _, entry := range cim.Entries {
			c.drawPoint(img, entry.Latitude, entry.Longitude, float32(intScale)/float32(2))
		}
	}
	ctx.ContentType("image/png")
	png.Encode(ctx.ResponseWriter, img)
}
Ejemplo n.º 18
0
func getSong(ctx *web.Context, songLoc string) string {
	song := musicDir + "/" + songLoc
	f, err := os.Open(song)
	if err != nil {
		return "Error reading file!\n"
	}

	//Get MIME
	r, err := ioutil.ReadAll(f)
	if err != nil {
		return "Error reading file!\n"
	}
	mime := http.DetectContentType(r)

	_, err = f.Seek(0, 0)
	if err != nil {
		return "Error reading the file\n"
	}
	ctx.ContentType(mime)
	http.ServeContent(ctx.ResponseWriter, ctx.Request, song, time.Now(), f)
	return ""
}
Ejemplo n.º 19
0
Archivo: api.go Proyecto: 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
	}
}
Ejemplo n.º 20
0
Archivo: server.go Proyecto: nfleet/via
func Splash(ctx *web.Context) {
	ctx.ContentType("image/jpeg")
	http.ServeFile(ctx, ctx.Request, "./splash.jpg")
}
Ejemplo n.º 21
0
func allHexagrams(ctx *web.Context) string {
	hexagrams := iching.GetAllHexagrams()
	ctx.ContentType("json")
	js, _ := json.Marshal(hexagrams)
	return string(js)
}