Skip to content
This repository has been archived by the owner on May 6, 2024. It is now read-only.

Commit

Permalink
New endpoint to process a list of image paths.
Browse files Browse the repository at this point in the history
  • Loading branch information
Skarlso committed Apr 6, 2018
1 parent 32a3cf5 commit 4e455da
Showing 1 changed file with 50 additions and 15 deletions.
65 changes: 50 additions & 15 deletions receiver/main.go
@@ -1,8 +1,10 @@
package main

import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"

Expand All @@ -16,44 +18,77 @@ func init() {
configuration.loadConfiguration()
}

// Path is a path to an image
// Path is a single path of an image to process.
type Path struct {
Path string `json:"path"`
}

// Paths is a batch of paths to process.
type Paths struct {
Paths []Path `json:"paths"`
}

// PostImage handles a post of an image. Saves it to the database
// and sends it to NSQ for further processing.
func PostImage(w http.ResponseWriter, r *http.Request) {
var p Path
err := json.NewDecoder(r.Body).Decode(&p)
if err != nil {
fmt.Fprintf(w, "got error: %s", err)
fmt.Fprintf(w, "got error while decoding body: %s", err)
return
}
fmt.Fprintf(w, "got path: %+v\n", p)
image := Image{
ID: -1,
PersonID: -1,
Path: []byte(p.Path),
Status: PENDING,
}
err = image.saveImage()
fmt.Fprintf(w, "image saved with id: %d\n", image.ID)
var ps Paths
paths := make([]Path, 0)
paths = append(paths, p)
ps.Paths = paths
var pathsJSON bytes.Buffer
err = json.NewEncoder(&pathsJSON).Encode(ps)
if err != nil {
fmt.Fprintf(w, "got error while saving image: %s", err)
fmt.Fprintf(w, "failed to encode paths: %s", err)
return
}
nsq := new(NSQ)
err = nsq.sendImage(image)
r.Body = ioutil.NopCloser(&pathsJSON)
r.ContentLength = int64(pathsJSON.Len())
PostImages(w, r)
}

// PostImages handles a post of an image. Saves it to the database
// and sends it to NSQ for further processing.
func PostImages(w http.ResponseWriter, r *http.Request) {
var p Paths
err := json.NewDecoder(r.Body).Decode(&p)
if err != nil {
fmt.Fprintf(w, "error while sending image to queue: %s", err)
fmt.Fprintf(w, "got error while decoding request body: %s", err)
return
}
fmt.Fprintln(w, "image sent to nsq")
fmt.Fprintf(w, "got paths: %+v\n", p)
nsq := new(NSQ)
for _, path := range p.Paths {
image := Image{
ID: -1,
PersonID: -1,
Path: []byte(path.Path),
Status: PENDING,
}
err = image.saveImage()
if err != nil {
fmt.Fprintf(w, "got error while saving image: %s; moving on to next...", err)
continue
}
fmt.Fprintf(w, "image saved with id: %d\n", image.ID)
err = nsq.sendImage(image)
if err != nil {
fmt.Fprintf(w, "error while sending image to queue: %s", err)
continue
}
fmt.Fprintln(w, "image sent to nsq")
}
}

func main() {
router := mux.NewRouter()
router.HandleFunc("/image/post", PostImage).Methods("POST")
router.HandleFunc("/images/post", PostImages).Methods("POST")
log.Fatal(http.ListenAndServe(":8000", router))
}

0 comments on commit 4e455da

Please sign in to comment.