-
Notifications
You must be signed in to change notification settings - Fork 64
/
main.go
99 lines (91 loc) · 2.76 KB
/
main.go
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
95
96
97
98
99
package main
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
"time"
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
_ "github.com/lib/pq"
"github.com/narenaryan/jsonstore/models"
)
// DB stores the database session imformation. Needs to be initialized once
type DBClient struct {
db *gorm.DB
}
// UserResponse is the response to be send back for User
type UserResponse struct {
User models.User `json:"user"`
Data interface{} `json:"data"`
}
// GetUsersByFirstName fetches the original URL for the given encoded(short) string
func (driver *DBClient) GetUsersByFirstName(w http.ResponseWriter, r *http.Request) {
var users []models.User
name := r.FormValue("first_name")
// Handle response details
var query = "select * from \"user\" where data->>'first_name'=?"
driver.db.Raw(query, name).Scan(&users)
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
//responseMap := map[string]interface{}{"url": ""}
respJSON, _ := json.Marshal(users)
w.Write(respJSON)
}
// GetUser fetches the original URL for the given encoded(short) string
func (driver *DBClient) GetUser(w http.ResponseWriter, r *http.Request) {
var user = models.User{}
vars := mux.Vars(r)
// Handle response details
driver.db.First(&user, vars["id"])
var userData interface{}
// Unmarshal JSON string to interface
json.Unmarshal([]byte(user.Data), &userData)
var response = UserResponse{User: user, Data: userData}
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
//responseMap := map[string]interface{}{"url": ""}
respJSON, _ := json.Marshal(response)
w.Write(respJSON)
}
// PostUser adds URL to DB and gives back shortened string
func (driver *DBClient) PostUser(w http.ResponseWriter, r *http.Request) {
var user = models.User{}
postBody, _ := ioutil.ReadAll(r.Body)
user.Data = string(postBody)
driver.db.Save(&user)
responseMap := map[string]interface{}{"id": user.ID}
var err string = ""
if err != "" {
w.Write([]byte("yes"))
} else {
w.Header().Set("Content-Type", "application/json")
response, _ := json.Marshal(responseMap)
w.Write(response)
}
}
func main() {
db, err := models.InitDB()
if err != nil {
panic(err)
}
dbclient := &DBClient{db: db}
if err != nil {
panic(err)
}
defer db.Close()
// Create a new router
r := mux.NewRouter()
// Attach an elegant path with handler
r.HandleFunc("/v1/user/{id:[a-zA-Z0-9]*}", dbclient.GetUser).Methods("GET")
r.HandleFunc("/v1/user", dbclient.PostUser).Methods("POST")
r.HandleFunc("/v1/user", dbclient.GetUsersByFirstName).Methods("GET")
srv := &http.Server{
Handler: r,
Addr: "127.0.0.1:8000",
// Good practice: enforce timeouts for servers you create!
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
log.Fatal(srv.ListenAndServe())
}