72 lines
1.7 KiB
Go
72 lines
1.7 KiB
Go
package restserver
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
resultstruct "git.ukamnya.ru/stulyaganov/RestApi/internal/restserver/resultStruct"
|
|
"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)
|
|
cout, err := r.db.Films().GetCountFilms()
|
|
if err != nil {
|
|
r.logger.Errorln(err)
|
|
}
|
|
io.WriteString(w, strconv.Itoa(*cout))
|
|
}
|
|
}
|
|
|
|
func (r *RestServer) HendleFindAll() http.HandlerFunc {
|
|
var filmData resultstruct.Films
|
|
data, err := r.db.Films().FindByAll()
|
|
if err != nil {
|
|
r.logger.Errorln(err)
|
|
}
|
|
cout, err := r.db.Films().GetCountFilms()
|
|
if err != nil {
|
|
r.logger.Errorln(err)
|
|
filmData.Result = false
|
|
} else {
|
|
filmData.Result = true
|
|
filmData.Data = *data
|
|
filmData.LastPage = *cout
|
|
}
|
|
jsonData, err := json.Marshal(filmData)
|
|
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))
|
|
}
|
|
}
|