Skip to content

Instantly share code, notes, and snippets.

@bdelacretaz
Last active April 6, 2017 12:41
Show Gist options
  • Save bdelacretaz/49ea40145e393eb1163fe6d7e7a00fa1 to your computer and use it in GitHub Desktop.
Save bdelacretaz/49ea40145e393eb1163fe6d7e7a00fa1 to your computer and use it in GitHub Desktop.
package main
// I'm a total beginner in Go, please have mercy ;-)
// Reads a JSON input object with an "url" field that points to an image file
// Uses exiftool to extract file metadata
// Outputs a JSON document with that metadata + request information
import (
"bufio"
"encoding/json"
"log"
"os"
"os/exec"
"strings"
"time"
)
const EXIF_TOOL string = "exiftool"
// TODO json package only accesses exported fields like with names that
// begin with an uppercase letter - how to specify lowercased keys?
// (json: tag like Metadata here is ugly)
type OutputFormat struct {
Request struct {
AssetID string
InputFile string
Processor string
Info string
DurationMilliseconds time.Duration
}
Output struct {
Metadata map[string]string `json:"metadata"`
}
}
func getInputURI() string {
dec := json.NewDecoder(os.Stdin)
for {
var v map[string]interface{}
if err := dec.Decode(&v); err != nil {
panic("JSON parsing error")
}
return v["url"].(string)
}
}
func main() {
var start = time.Now()
var inputURI = getInputURI()
var inputFile = strings.TrimPrefix(inputURI, "file://")
log.Print("Input file ", inputFile)
cmd := exec.Command(EXIF_TOOL, inputFile)
pipe, err := cmd.StdoutPipe()
if err != nil {
panic(err)
}
scanner := bufio.NewScanner(pipe)
if err := cmd.Start(); err != nil {
panic(err)
}
var m map[string]string
m = make(map[string]string)
for scanner.Scan() {
fields := strings.Split(scanner.Text(), ":")
m[strings.Trim(fields[0], " ")] = strings.Trim(fields[1], " ")
}
output := &OutputFormat{}
output.Request.AssetID = inputURI
output.Request.InputFile = inputFile
output.Request.Processor = EXIF_TOOL
output.Request.Info = "Image metadata generated by " + EXIF_TOOL
output.Request.DurationMilliseconds = time.Since(start) / 1000000
output.Output.Metadata = m
enc := json.NewEncoder(os.Stdout)
if err := enc.Encode(&output); err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment