예제 #1
0
func (p *proxy) serveExistingFile(w http.ResponseWriter, r *http.Request) bool {
	reqFile := r.URL.Path[1:]
	cachedFile := p.cacheDir + reqFile

	if common.FileExists(cachedFile) {

		f, err := os.Open(cachedFile)
		if err != nil {
			if false == os.IsNotExist(err) {
				common.InfoErr("Cannot open %q because %s\n", cachedFile, err.Error())
			}
			return false
		}
		defer func() {
			if err := f.Close(); err != nil {
				common.InfoErr("Failed to close file %q with Error %s\n", reqFile, err)
			}
		}()

		addHeaders(filepath.Ext(reqFile), cacheUntil, w)
		if _, err := io.Copy(w, f); err != nil {
			common.InfoErr("Error copying file content to http response: %s with file %q", err, reqFile)
			return false
		}
		return true
	}
	return false
}
예제 #2
0
func newHandle(ctx *cli.Context) *handle {
	csvFile := ctx.String("csv")
	var rec [][]string
	if csvFile != "" {
		rec = record.GetCSVContent(csvFile)
	}

	h := &handle{
		proxy:   newProxy(ctx),
		fileMap: make(map[string]record.Record),
		pattern: ctx.String("img-pattern"),
	}
	h.Lock()
	defer h.Unlock()

	if vif := ctx.String("img-config"); vif != "" {
		var err error
		if h.virtualImages, err = parseVirtualImageConfigFile(vif); err != nil {
			common.InfoErr("File %s contains error:\n%s\n", vif, err)
		}
	}

	h.fileMap["favicon.ico"] = record.NewRecordFields("icon", "favicon.ico", 16, 16)
	for _, row := range rec {
		rec, err := record.NewRecord(h.pattern, row...)
		if err != nil {
			common.InfoErr("File %s contains error: %s\n", csvFile, err)
		}
		rec.Path = ctx.String("url-prefix") + rec.Path
		h.fileMap[rec.Path] = rec
	}
	h.length = len(rec)
	return h
}
예제 #3
0
func (w *traverse) close() {

	w.workerStop <- struct{}{}
	close(w.workerRec)

	if err := w.outW.Close(); err != nil {
		common.InfoErr("GZIP close error: %s\n", err)
	}
	if err := w.outF.Close(); err != nil {
		common.InfoErr("File close error: %s\n", err)
	}

	w.bar.Finish()
	fmt.Fprintf(w.cliWriter, "Wrote to file: %s\n", w.outfile)
}
예제 #4
0
func (h *handle) rootJSON(w http.ResponseWriter, r *http.Request) {
	w.Header().Set(ContentType, ApplicationJSONCharsetUTF8)
	h.RLock()

	//if err := json.NewEncoder(w).Encode(h.virtualImages); err != nil {
	//	common.InfoErr("Failed to write JSON encoded virtual image configuration with error: %s\n", err)
	//}

	for _, rec := range h.fileMap {
		if err := rec.ToJSON(w); err != nil {
			common.InfoErr("Failed to write JSON with error: %s\n", err)
		}
		if _, err := w.Write(brByte); err != nil {
			common.InfoErr("Failed to write JSON with error: %s\n", err)
		}
	}
	h.RUnlock()
}
예제 #5
0
func getImageDimension(imagePath string) (int, int) {
	file, err := os.Open(imagePath)
	if err != nil {
		common.InfoErr("Cannot open image: %s\n", err)
		return 0, 0

	}

	image, _, err := image.DecodeConfig(file)
	if err != nil {
		common.InfoErr("Image %s decoding error: %s\n", imagePath, err)
		return 0, 0
	}

	if err := file.Close(); err != nil {
		common.InfoErr("Close error: %s: %s\n", imagePath, err)
		return 0, 0
	}
	return image.Width, image.Height
}
예제 #6
0
// post or get request
// $ curl --data "file=media/catalog/product/1/2/120---microsoft-natural-ergonomic-keyboard-4000.jpg" http://127.0.0.1:4711/fileDetails
// and returns:
// {"Path":"media/catalog/product/1/2/120---microsoft-natural-ergonomic-keyboard-4000.jpg","ModTime":"2014-02-16T03:27:45+01:00","Width":5184,"Height":3456}
func (h *handle) fileDetails(w http.ResponseWriter, r *http.Request) {
	filePath := r.FormValue("file")
	if filePath == "" {
		http.NotFound(w, r)
		return
	}

	h.RLock()
	defer h.RUnlock()

	rec, ok := h.fileMap[filePath]
	if !ok {
		common.InfoErr("%s not found in CSV file\n", filePath)
		http.NotFound(w, r)
		return
	}
	w.Header().Set(ContentType, ApplicationJSONCharsetUTF8)
	if err := rec.ToJSON(w); err != nil {
		common.InfoErr("Failed to write JSON with error: %s\n", err)
	}
}
예제 #7
0
func (r Record) CreateContent(f string, w io.Writer) {
	switch r.ext {
	case ".png":
		if err := png.Encode(w, r.generateImage()); err != nil {
			common.InfoErr("Failed to create PNG file %s with error: %s\n", f, err)
		}
	case ".jpg", ".jpeg":
		// big file size? reason why is here: https://www.reddit.com/r/golang/comments/3kn1zp/filesize_of_jpegencode/
		if err := jpeg.Encode(w, r.generateImage(), &jpeg.Options{Quality: 75}); err != nil {
			common.InfoErr("Failed to create JPEG file %s with error: %s\n", f, err)
		}
	case ".gif", ".ico":
		if err := gif.Encode(w, r.generateImage(), nil); err != nil {
			common.InfoErr("Failed to create GIF file %s with error: %s\n", f, err)
		}
	default:
		if _, err := w.Write(nil); err != nil {
			common.InfoErr("Failed to write file %s with error: %s\n", f, err)
		}
	}
}
예제 #8
0
func (r Record) CreateFile(basePath string) error {

	d, f := r.getDirFile(basePath)
	if err := os.MkdirAll(d, DirPerm); err != nil {
		common.UsageAndExit("Failed to create directory: %s with error: %s", d, err)
	}

	file, err := os.Create(d + f)
	if err != nil {
		return fmt.Errorf("Failed to create file %s%s", d, f)
	}
	defer func() {
		if err := file.Close(); err != nil {
			common.InfoErr("Failed to close file %s with error: %s\n", d+f, err)
		}
	}()

	if err := os.Chtimes(d+f, r.ModTime, r.ModTime); err != nil {
		common.InfoErr("Failed to change time for file %s with error: %s\n", d+f, err)
	}
	r.CreateContent(f, file)

	return nil
}
예제 #9
0
func (p *proxy) serveAndSaveRemoteFile(w http.ResponseWriter, r *http.Request) bool {
	reqFile := r.URL.Path[1:]
	cachedFile := p.cacheDir + reqFile
	remoteFile := p.url + reqFile

	resp, err := http.Get(remoteFile)
	defer func() {
		if resp.Body != nil {
			if err := resp.Body.Close(); err != nil {
				common.UsageAndExit("Failed to close URL %q with error: %s", remoteFile, err)
			}
		}
	}()

	if err != nil {
		common.InfoErr("Failed to download %q with error: %s\n", remoteFile, err)
		return false
	}
	if resp.StatusCode != http.StatusOK {
		common.InfoErr("Failed to download %q with Code: %q\n", remoteFile, http.StatusText(resp.StatusCode))
		return false
	}

	if dcf := filepath.Dir(cachedFile); false == common.IsDir(dcf) {
		if err := os.MkdirAll(dcf, 0755); err != nil {
			common.InfoErr("Failed to create cache folder %q with Code: %s\n", dcf, err)
			return false
		}
	}

	fw, err := os.OpenFile(cachedFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
	if err != nil {
		common.InfoErr("Failed to open write file %q for URL %q with Error: %s\n", cachedFile, remoteFile, err)
		return false
	}
	defer func() {
		if err := fw.Close(); err != nil {
			common.InfoErr("Failed to close write file %q from URL %q with Error %s\n", cachedFile, remoteFile, err)
		}
	}()

	addHeaders(filepath.Ext(reqFile), cacheUntil, w)
	mw := io.MultiWriter(w, fw)
	if _, err := io.Copy(mw, io.LimitReader(resp.Body, maxHttpDownloadSize)); err != nil {
		common.InfoErr("Failed to write to http response and/or file to disk: %q with error: %s. Max Size: %d KBytes\n", remoteFile, err, maxHttpDownloadSize/1024)
		return false
	}

	return true
}
예제 #10
0
func (h *handle) rootHTML(w http.ResponseWriter, r *http.Request) {
	h.RLock()
	defer h.RUnlock()
	w.Header().Set(ContentType, TextHTMLCharsetUTF8)
	fmt.Fprint(w, `<html>	<head><title>Mediamock Content Table</title></head>	<body><table>`)
	fmt.Fprint(w, `<thead><tr>
			<th>ModTime</th>
			<th nowrap>Width px</th>
			<th nowrap>Height px</th>
			<th>Link</th>
	</tr></thead><tbody>`)

	for path, vis := range h.virtualImages {
		for _, vi := range vis {
			_, err := fmt.Fprintf(w, `<tr>
			<td>n/a</td>
			<td>%d</td>
			<td>%d</td>
			<td><a href="%s" target="_blank">%s</a> Regex: %s</td>
		</tr>`,
				vi.Width,
				vi.Height,
				path, path, vi.regex,
			)
			if err != nil {
				common.InfoErr("Failed to write HTML table with error: %s\n", err)
			}

			if _, err := w.Write(brByte); err != nil {
				common.InfoErr("Failed to write brByte with error: %s\n", err)
			}
		}
	}

	var pathSlice = make(sort.StringSlice, len(h.fileMap))
	var i int
	for key, _ := range h.fileMap {
		pathSlice[i] = key
		i++
	}
	pathSlice.Sort()

	for _, key := range pathSlice {
		rec := h.fileMap[key]

		_, err := fmt.Fprintf(w, `<tr>
			<td>%s</td>
			<td>%d</td>
			<td>%d</td>
			<td><a href="%s" target="_blank">%s</a></td>
		</tr>`,
			rec.ModTime,
			rec.Width,
			rec.Height,
			rec.Path, rec.Path,
		)
		if err != nil {
			common.InfoErr("Failed to write HTML table with error: %s\n", err)
		}

		if _, err := w.Write(brByte); err != nil {
			common.InfoErr("Failed to write brByte with error: %s\n", err)
		}

	}

	fmt.Fprint(w, `</tbody></table></body>	</html>`)
}