goImgServer/handlers.go
handlers.goRaw
1package main
2
3import (
4 "encoding/json"
5 "fmt"
6 "io"
7 "io/ioutil"
8 "net/http"
9
10 "github.com/gorilla/mux"
11)
12
13func Index(w http.ResponseWriter, r *http.Request) {
14 fmt.Fprintln(w, "Welcome! To send images, go to /image")
15}
16
17func ImageShow(w http.ResponseWriter, r *http.Request) {
18 vars := mux.Vars(r)
19 imageName := vars["imageName"]
20 fmt.Fprintln(w, "Image show:", imageName)
21}
22
23func NewImage(w http.ResponseWriter, r *http.Request) {
24 var img ImageModel
25 body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
26 if err != nil {
27 panic(err)
28 }
29 if err := r.Body.Close(); err != nil {
30 panic(err)
31 }
32 fmt.Println(string(body))
33 if err := json.Unmarshal(body, &img); err != nil {
34 w.Header().Set("Content-Type", "application/json; charset=UTF-8")
35 w.WriteHeader(422) // unprocessable entity
36 if err := json.NewEncoder(w).Encode(err); err != nil {
37 panic(err)
38 }
39 }
40 img.File = body
41 fmt.Println(img)
42 fmt.Println(img.File)
43
44 w.Header().Set("Content-Type", "application/json; charset=UTF-8")
45 w.WriteHeader(http.StatusCreated)
46 if err := json.NewEncoder(w).Encode(img.File); err != nil {
47 panic(err)
48 }
49}