-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuser.go
More file actions
91 lines (66 loc) · 1.79 KB
/
user.go
File metadata and controls
91 lines (66 loc) · 1.79 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
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
"log"
"net/http"
)
type User struct {
gorm.Model
Name string
Email string
}
func allUsers(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")
vars := mux.Vars(r)
var u User
db.Where("Name = ?", vars["Name"]).First(&u)
json.NewEncoder(w).Encode(u)
}
func newUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var u User
_ = json.NewDecoder(r.Body).Decode(&u)
if u.Email != "" && u.Name != "" {
if err := db.Create(&User{Name: u.Name, Email: u.Email}).Error; err != nil {
log.Println(err.Error())
json.NewEncoder(w).Encode(err.Error())
}
json.NewEncoder(w).Encode(u)
} else {
log.Println("Email and Name are mandatory")
json.NewEncoder(w).Encode("Email and Name are mandatory")
}
}
func deleteUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
vars := mux.Vars(r)
var u User
if err := db.Where("Name = ?", vars["Name"]).First(&u).Error; err != nil {
log.Println(err.Error())
json.NewEncoder(w).Encode(err.Error())
} else {
db.Delete(&u)
json.NewEncoder(w).Encode("User Succesfully deleted")
}
}
func updateUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
vars := mux.Vars(r)
name := vars["name"]
email := vars["email"]
var user User
db.Where("name = ?", name).Find(&user)
user.Email = email
db.Save(&user)
fmt.Fprintf(w, "User Successfully Updated")
}