Skip to content

Instantly share code, notes, and snippets.

@marcinwyszynski
Last active August 29, 2015 14:21
Show Gist options
  • Save marcinwyszynski/b47bda5c598b846431d6 to your computer and use it in GitHub Desktop.
Save marcinwyszynski/b47bda5c598b846431d6 to your computer and use it in GitHub Desktop.
package main
import (
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
)
var (
dest = flag.String("dest", "", "file name to store the latest image")
port = flag.Int("port", 3000, "http port to run on")
)
type httpHandler func(w http.ResponseWriter, r *http.Request)
type fallibleHandler func(w http.ResponseWriter, r *http.Request) error
func handleOrLog(handler fallibleHandler) httpHandler {
return func(w http.ResponseWriter, r *http.Request) {
if err := handler(w, r); err != nil {
log.Printf("error %v, expected nil", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
}
func uploadImage(w http.ResponseWriter, r *http.Request) error {
tmpfile, err := ioutil.TempFile("/tmp", "food")
if err != nil {
return err
}
defer r.Body.Close()
if _, err := io.Copy(tmpfile, r.Body); err != nil {
return err
}
if err := tmpfile.Close(); err != nil {
return err
}
if err := os.Rename(filepath.Join("/tmp", tmpfile.Name()), *dest); err != nil {
return err
}
w.WriteHeader(http.StatusAccepted)
return nil
}
func showImage(w http.ResponseWriter, r *http.Request) error {
file, err := os.Open(*dest)
if err != nil {
return err
}
defer file.Close()
_, err = io.Copy(w, file)
return err
}
func main() {
flag.Parse()
http.HandleFunc("/upload", handleOrLog(uploadImage))
http.HandleFunc("/show", handleOrLog(showImage))
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", *port), nil))
}
@marcinwyszynski
Copy link
Author

added error handling

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment