-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
94 lines (79 loc) · 2.22 KB
/
main.go
File metadata and controls
94 lines (79 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
var DB *gorm.DB
var err error
//used the local database her i.e "mysql"
//passed the url to connect to the data base
//as I'm using mysql db,we have installed mysql driver here
const DNS = "root:admin@tcp(127.0.0.1:3306)/godb?charset=utf8mb4&parseTime=True&loc=Local"
type User struct {
gorm.Model
FirstName string `json:"firstname"`
LastName string `json:"lastname"`
Email string `json:"email"`
}
func InitialMigration() {
DB, err = gorm.Open(mysql.Open(DNS), &gorm.Config{})
if err != nil {
fmt.Println(err.Error())
panic("Cannot connect to DB")
}
DB.AutoMigrate(&User{})
}
func GetUsers(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
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")
params := mux.Vars(r)
var user User
DB.First(&user, params["id"])
json.NewEncoder(w).Encode(user)
}
func CreateUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var user User
json.NewDecoder(r.Body).Decode(&user)
DB.Create(&user)
json.NewEncoder(w).Encode(user)
}
func UpdateUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(r)
var user User
DB.First(&user, params["id"])
json.NewDecoder(r.Body).Decode(&user)
DB.Save(&user)
json.NewEncoder(w).Encode(user)
}
func DeleteUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(r)
var user User
DB.Delete(&user, params["id"])
json.NewEncoder(w).Encode("The USer is Deleted Successfully!")
}
func handleRequest() {
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(":9000", r))
}
func main() {
InitialMigration()
handleRequest()
}