Commit 498eb686 authored by Muhammad, Hammad's avatar Muhammad, Hammad

rest api with mysql db

parent 6b723dd8
POST http://localhost:8080/books
Content-Type: application/json
{
"id" : "1",
"title" : "The Godfather",
"author" : "Mario Puzo"
}
###
GET http://localhost:8080/books
\ No newline at end of file
package main
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
func GetMySQLDB() (db *sql.DB, err error) {
dbDriver := "mysql"
dbUser := "root"
dbPass := ""
dbName := "books"
db, err = sql.Open(dbDriver, dbUser+":"+dbPass+"@/"+dbName)
return
}
......@@ -4,9 +4,7 @@ go 1.20
require (
github.com/gin-gonic/gin v1.9.0
github.com/golang-jwt/jwt v3.2.2+incompatible
gorm.io/driver/sqlite v1.4.4
gorm.io/gorm v1.24.6
github.com/go-sql-driver/mysql v1.7.0
)
require (
......@@ -17,13 +15,10 @@ require (
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.11.2 // indirect
github.com/goccy/go-json v0.10.0 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.0.9 // indirect
github.com/leodido/go-urn v1.2.1 // indirect
github.com/mattn/go-isatty v0.0.17 // indirect
github.com/mattn/go-sqlite3 v1.14.15 // indirect
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.0.6 // indirect
......
......@@ -18,19 +18,14 @@ github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJn
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.11.2 h1:q3SHpufmypg+erIExEKUmsgmhDTyhcJ38oeKGACXohU=
github.com/go-playground/validator/v10 v10.11.2/go.mod h1:NieE624vt4SCTJtD87arVLvdmjPAeV8BQlHtMnw9D7s=
github.com/go-sql-driver/mysql v1.7.0 h1:ueSltNNllEqE3qcWBTD0iQd3IpL/6U+mJxLkazJ7YPc=
github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
github.com/goccy/go-json v0.10.0 h1:mXKd9Qw4NuzShiRlOXKews24ufknHO7gx30lsDyokKA=
github.com/goccy/go-json v0.10.0/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.4/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4=
......@@ -41,8 +36,6 @@ github.com/leodido/go-urn v1.2.1 h1:BqpAaACuzVSgi/VLzGZIobT2z4v53pjosyNd9Yv6n/w=
github.com/leodido/go-urn v1.2.1/go.mod h1:zt4jvISO2HfUBqxjfIshjdMTYS56ZS/qv49ictyFfxY=
github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng=
github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-sqlite3 v1.14.15 h1:vfoHhTN1af61xCRSWzFIWzx2YskyMTwHLrExkBOjvxI=
github.com/mattn/go-sqlite3 v1.14.15/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
......@@ -87,9 +80,4 @@ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntN
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/sqlite v1.4.4 h1:gIufGoR0dQzjkyqDyYSCvsYR6fba1Gw5YKDqKeChxFc=
gorm.io/driver/sqlite v1.4.4/go.mod h1:0Aq3iPO+v9ZKbcdiz8gLWRw5VOPcBOPUQJFLq5e2ecI=
gorm.io/gorm v1.24.0/go.mod h1:DVrVomtaYTbqs7gB/x2uVvqnXzv0nqjB396B8cG4dBA=
gorm.io/gorm v1.24.6 h1:wy98aq9oFEetsc4CAbKD2SoBCdMzsbSIvSUUFJuHi5s=
gorm.io/gorm v1.24.6/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k=
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
......@@ -3,86 +3,35 @@ package main
import (
"fmt"
"net/http"
"strings"
"time"
"database/sql"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
func main() {
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
db, err := sql.Open("mysql", "root:@tcp(127.0.0.1:3306)/books")
defer db.Close()
if err != nil {
panic("failed to connect database")
}
db.AutoMigrate(&Book{})
handler := newHandler(db)
r := gin.New()
r.POST("/login", loginHandler)
protected := r.Group("/", authorizationMiddleware)
protected.GET("/books", handler.listBooksHandler)
protected.POST("/books", handler.createBookHandler)
protected.DELETE("/books/:id", handler.deleteBookHandler)
r.GET("/books", handler.listBooksHandler)
r.POST("/books", handler.createBookHandler)
r.DELETE("/books/:id", handler.deleteBookHandler)
r.Run()
}
func loginHandler(c *gin.Context) {
// implement login logic here
token := jwt.NewWithClaims(jwt.SigningMethodHS256, &jwt.StandardClaims{
ExpiresAt: time.Now().Add(5 * time.Minute).Unix(),
})
ss, err := token.SignedString([]byte("MySignature"))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
}
c.JSON(http.StatusOK, gin.H{
"token": ss,
})
}
func authorizationMiddleware(c *gin.Context) {
s := c.Request.Header.Get("Authorization")
token := strings.TrimPrefix(s, "Bearer ")
if err := validateToken(token); err != nil {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
}
func validateToken(token string) error {
_, err := jwt.Parse(token, func(t *jwt.Token) (interface{}, error) {
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
}
return []byte("MySignature"), nil
})
return err
}
type Handler struct {
db *gorm.DB
db *sql.DB
}
func newHandler(db *gorm.DB) *Handler {
func newHandler(db *sql.DB) *Handler {
return &Handler{db}
}
......@@ -95,31 +44,70 @@ type Book struct {
func (h *Handler) listBooksHandler(c *gin.Context) {
var books []Book
if result := h.db.Find(&books); result.Error != nil {
rows, err := h.db.Query("SELECT ID,Title,Author FROM Book_Record")
var id, title, author string
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err,
})
return
}
for rows.Next() {
err := rows.Scan(&id, &title, &author)
if err != nil { /* error handling */
}
books = append(books, Book{ID: id, Title: title, Author: author})
}
c.JSON(http.StatusOK, &books)
}
func (h *Handler) createBookHandler(c *gin.Context) {
var book Book
if err := c.BindJSON(&book); err != nil {
if err := c.ShouldBindJSON(&book); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
return
}
if result := h.db.Create(&book); result.Error != nil {
return
sql := "INSERT INTO Book_Record(ID,Title,Author) VALUES (?,?,?)"
insert, err := h.db.Prepare(sql)
if err != nil {
panic(err.Error())
}
resp, err := insert.Exec(book.ID, book.Title, book.Author)
insert.Close()
if err != nil {
fmt.Println(err)
}
lastId, err := resp.LastInsertId()
if err != nil {
panic(err)
}
fmt.Printf("The last inserted row id: %d\n", lastId)
c.JSON(http.StatusCreated, &book)
}
func (h *Handler) deleteBookHandler(c *gin.Context) {
id := c.Param("id")
if result := h.db.Delete(&Book{}, id); result.Error != nil {
_, err := h.db.Exec("delete FROM Book_Record where ID = ?", id)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err,
})
return
}
......
File deleted
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment