Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Crud api #83

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions beginner/CRUD_API/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
module golangexample/sampleapp

go 1.19

require (
github.com/gorilla/mux v1.8.0
github.com/jinzhu/gorm v1.9.16
gorm.io/gorm v1.24.0
)

require (
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.4 // indirect
github.com/mattn/go-sqlite3 v1.14.15 // indirect
)
25 changes: 25 additions & 0 deletions beginner/CRUD_API/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package main

import (
"log"
"net/http"

"github.com/gorilla/mux"
)

func initializeRouter() {
r := mux.NewRouter()

r.HandleFunc("/users", GetUsers).Methods("GET")
r.HandleFunc("/users/{id}", GetUser).Methods("GET")
r.HandleFunc("/users", CreateUser).Methods("POST")
r.HandleFunc("/users/{id}", UpdateUser).Methods("PUT")
r.HandleFunc("/users/{id}", DeleteUser).Methods("DELETE")

log.Fatal(http.ListenAndServe(":9001", r))
}

func main() {
IntialMigration()
initializeRouter()
}
95 changes: 95 additions & 0 deletions beginner/CRUD_API/user.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
package main

import (
"encoding/json"
"net/http"

"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)


var DB *gorm.DB
var err error


//Gorm is used to convert our struct into a model struct so that we can store date in db using ORM
type User struct{

gorm.Model
FirstName string `json:"first_name"`
LasName string `json:"last_name"`
Email string `json:"email"`


}

func IntialMigration(){
DB, err = gorm.Open("sqlite3", "user.db")
if err != nil {
panic("Failed to open the SQLite database.")
}
//defer DB.Close()

// Create the table from our struct
DB.AutoMigrate(&User{})


}

//arguments includes the response writer and the a pointer pointing to the actual request that came in
func GetUsers(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
//slice
var users []User
DB.Find(&users)
json.NewEncoder(w).Encode(users)

}

func GetUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var user User
params :=mux.Vars(r)
DB.First(&user,params["id"])
json.NewEncoder(w).Encode(user)

}

func DeleteUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var user User
params :=mux.Vars(r)
DB.Delete(&user,params["id"])
json.NewEncoder(w).Encode("The user is deleted")

}

func CreateUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var user User
err := json.NewDecoder(r.Body).Decode(&user)
if err!= nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
DB.Create(&user)
json.NewEncoder(w).Encode(user)



}

func UpdateUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var user User
params :=mux.Vars(r)
DB.First(&user,params["id"])
json.NewDecoder(r.Body).Decode(&user)
DB.Save(&user)
json.NewEncoder(w).Encode(user)


}