Browse Source

REST architecture implemented

master
arnaucode 7 years ago
parent
commit
75c384c9f3
6 changed files with 149 additions and 0 deletions
  1. +49
    -0
      handlers.go
  2. +5
    -0
      imageModel.go
  3. +23
    -0
      logger.go
  4. +13
    -0
      main.go
  5. +24
    -0
      router.go
  6. +35
    -0
      routes.go

+ 49
- 0
handlers.go

@ -0,0 +1,49 @@
package main
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"github.com/gorilla/mux"
)
func Index(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Welcome! To send images, go to /image")
}
func ImageShow(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
imageName := vars["imageName"]
fmt.Fprintln(w, "Image show:", imageName)
}
func NewImage(w http.ResponseWriter, r *http.Request) {
var img ImageModel
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
if err != nil {
panic(err)
}
if err := r.Body.Close(); err != nil {
panic(err)
}
fmt.Println(string(body))
if err := json.Unmarshal(body, &img); err != nil {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(422) // unprocessable entity
if err := json.NewEncoder(w).Encode(err); err != nil {
panic(err)
}
}
img.File = body
fmt.Println(img)
fmt.Println(img.File)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusCreated)
if err := json.NewEncoder(w).Encode(img.File); err != nil {
panic(err)
}
}

+ 5
- 0
imageModel.go

@ -0,0 +1,5 @@
package main
type ImageModel struct {
File []byte `json:"file"`
}

+ 23
- 0
logger.go

@ -0,0 +1,23 @@
package main
import (
"log"
"net/http"
"time"
)
func Logger(inner http.Handler, name string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
inner.ServeHTTP(w, r)
log.Printf(
"%s\t%s\t%s\t%s",
r.Method,
r.RequestURI,
name,
time.Since(start),
)
})
}

+ 13
- 0
main.go

@ -0,0 +1,13 @@
package main
import (
"log"
"net/http"
)
func main() {
router := NewRouter()
log.Fatal(http.ListenAndServe(":3050", router))
}

+ 24
- 0
router.go

@ -0,0 +1,24 @@
package main
import (
"net/http"
"github.com/gorilla/mux"
)
func NewRouter() *mux.Router {
router := mux.NewRouter().StrictSlash(true)
for _, route := range routes {
var handler http.Handler
handler = route.HandlerFunc
handler = Logger(handler, route.Name)
router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(handler)
}
return router
}

+ 35
- 0
routes.go

@ -0,0 +1,35 @@
package main
import (
"net/http"
)
type Route struct {
Name string
Method string
Pattern string
HandlerFunc http.HandlerFunc
}
type Routes []Route
var routes = Routes{
Route{
"Index",
"GET",
"/",
Index,
},
Route{
"ImageShow",
"GET",
"/images/{imageName}",
ImageShow,
},
Route{
"NewImage",
"POST",
"/image",
NewImage,
},
}

Loading…
Cancel
Save