├── .gitignore └── lib └── server.go /.gitignore: -------------------------------------------------------------------------------- 1 | images 2 | ./server 3 | 4 | -------------------------------------------------------------------------------- /lib/server.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "crypto/sha1" 5 | "fmt" 6 | "io/ioutil" 7 | "net/http" 8 | ) 9 | 10 | /** 11 | * Image 12 | */ 13 | type Image struct { 14 | Data []byte 15 | Filename string 16 | SHA string 17 | } 18 | 19 | func (i *Image) save() error { 20 | return ioutil.WriteFile(i.Filename, i.Data, 0600) 21 | } 22 | 23 | func saveHandler(ext string, ImageRoot string) http.HandlerFunc { 24 | return func(w http.ResponseWriter, r *http.Request) { 25 | image, _ := ioutil.ReadAll(r.Body) 26 | SHA := fmt.Sprintf("%x", sha1.Sum(image)) 27 | fmt.Println("sha1 hash " + SHA) 28 | ImageFilename := SHA + "." + ext 29 | StoredFilename := ImageRoot + ImageFilename 30 | i := &Image{Data: []byte(image), Filename: StoredFilename, SHA: SHA} 31 | 32 | err := i.save() 33 | if err != nil { 34 | http.Error(w, err.Error(), http.StatusInternalServerError) 35 | return 36 | } 37 | 38 | RedirectToPathname := "/images/" + ImageFilename 39 | http.Redirect(w, r, RedirectToPathname, http.StatusFound) 40 | } 41 | } 42 | 43 | func main() { 44 | ImageRoot := "/home/stomlinson/cap.uk/images/" 45 | Port := ":10138" 46 | 47 | http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir(ImageRoot)))) 48 | http.HandleFunc("/jpeg", saveHandler("jpg", ImageRoot)) 49 | http.HandleFunc("/png", saveHandler("png", ImageRoot)) 50 | http.ListenAndServe(Port, nil) 51 | } 52 | --------------------------------------------------------------------------------