Created
June 9, 2019 07:24
-
-
Save ssaumyaranjan7/0227a497ce560652a313b62b8bbc630a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package controllers | |
import ( | |
"encoding/json" | |
"fmt" | |
"github.com/example/simple-REST/pkg/utils" | |
"github.com/gorilla/mux" | |
"net/http" | |
"strconv" | |
"github.com/example/simple-REST/pkg/models" | |
) | |
var NewBook models.Book | |
func CreateBook(w http.ResponseWriter, r *http.Request) { | |
CreateBook := &models.Book{} | |
utils.ParseBody(r, CreateBook) | |
b:= CreateBook.CreateBook() | |
res,_ := json.Marshal(b) | |
w.WriteHeader(http.StatusOK) | |
w.Write(res) | |
} | |
func GetBook(w http.ResponseWriter, r *http.Request) { | |
newBooks:= models.GetAllBooks() | |
res, _ := json.Marshal(newBooks) | |
w.Header().Set("Content-Type", "pkglication/json") | |
w.WriteHeader(http.StatusOK) | |
w.Write(res) | |
} | |
func GetBookById(w http.ResponseWriter, r *http.Request) { | |
vars := mux.Vars(r) | |
bookId := vars["bookId"] | |
ID, err:= strconv.ParseInt(bookId, 0, 0) | |
if err != nil { | |
fmt.Println("Error while parsing") | |
} | |
bookDetails, _:= models.GetBookById(ID) | |
res, _ := json.Marshal(bookDetails) | |
w.Header().Set("Content-Type", "pkglication/json") | |
w.WriteHeader(http.StatusOK) | |
w.Write(res) | |
} | |
func UpdateBook(w http.ResponseWriter, r *http.Request) { | |
var updateBook = &models.Book{} | |
utils.ParseBody(r, updateBook) | |
vars := mux.Vars(r) | |
bookId := vars["bookId"] | |
ID, err:= strconv.ParseInt(bookId, 0, 0) | |
if err != nil { | |
fmt.Println("Error while parsing") | |
} | |
bookDetails, db:= models.GetBookById(ID) | |
if updateBook.Name != "" { | |
bookDetails.Name = updateBook.Name | |
} | |
if updateBook.Author != "" { | |
bookDetails.Author = updateBook.Author | |
} | |
if updateBook.Publication != "" { | |
bookDetails.Publication = updateBook.Publication | |
} | |
db.Save(&bookDetails) | |
res, _ := json.Marshal(bookDetails) | |
w.Header().Set("Content-Type", "pkglication/json") | |
w.WriteHeader(http.StatusOK) | |
w.Write(res) | |
} | |
func DeleteBook(w http.ResponseWriter, r *http.Request) { | |
vars := mux.Vars(r) | |
bookId := vars["bookId"] | |
ID, err:= strconv.ParseInt(bookId, 0, 0) | |
if err != nil { | |
fmt.Println("Error while parsing") | |
} | |
book:= models.DeleteBook(ID) | |
res, _ := json.Marshal(book) | |
w.Header().Set("Content-Type", "pkglication/json") | |
w.WriteHeader(http.StatusOK) | |
w.Write(res) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment