RestApiv2/internal/restserver/filmhandle.go

57 lines
1.2 KiB
Go

package restserver
import (
"encoding/json"
"fmt"
"io"
"net/http"
"github.com/gorilla/mux"
)
func (r *RestServer) configureRouterFilms() {
r.router.HandleFunc("/api/hello", r.HandleHello()).Methods("GET")
r.router.HandleFunc("/api/films", r.HendleFindAll()).Methods("GET")
r.router.HandleFunc("/api/films/{id:[0-9]+}", r.HendleFindID()).Methods("GET")
}
func (r *RestServer) HandleHello() http.HandlerFunc {
return func(w http.ResponseWriter, res *http.Request) {
id := res.URL.Query().Get("id")
fmt.Println(id)
io.WriteString(w, id)
}
}
func (r *RestServer) HendleFindAll() http.HandlerFunc {
film, err := r.db.Films().FindByAll()
if err != nil {
r.logger.Errorln(err)
}
jsonData, err := json.Marshal(film)
if err != nil {
r.logger.Errorln(err)
}
return func(w http.ResponseWriter, res *http.Request) {
io.WriteString(w, string(jsonData))
}
}
func (r *RestServer) HendleFindID() http.HandlerFunc {
return func(w http.ResponseWriter, res *http.Request) {
id := mux.Vars(res)["id"]
film, err := r.db.Films().FindById(id)
if err != nil {
r.logger.Errorln(err)
}
jsonData, err := json.MarshalIndent(film, "", " ")
if err != nil {
r.logger.Errorln(err)
}
io.WriteString(w, string(jsonData))
}
}