Skip to content

Commit 6ef0f33

Browse files
committed
a better refactoring the application
1 parent d31c719 commit 6ef0f33

File tree

2 files changed

+147
-115
lines changed

2 files changed

+147
-115
lines changed

app.go

Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
package main
2+
3+
import (
4+
"database/sql"
5+
"encoding/json"
6+
"fmt"
7+
"io/ioutil"
8+
"log"
9+
"net/http"
10+
"strconv"
11+
12+
"github.com/gorilla/mux"
13+
_ "github.com/lib/pq"
14+
)
15+
16+
type App struct {
17+
Router *mux.Router
18+
DB *sql.DB
19+
}
20+
21+
func (a *App) Initialize(db_type, db_user, db_password, db_host, db_database string) {
22+
23+
connStr := fmt.Sprintf("%s://%s:%s@%s/%s?sslmode=disable", db_type, db_user, db_password, db_host, db_database)
24+
25+
var err error
26+
a.DB, err = sql.Open("postgres", connStr)
27+
if err != nil {
28+
log.Fatal(err)
29+
}
30+
31+
a.Router = mux.NewRouter()
32+
33+
a.initializeRoutes()
34+
}
35+
36+
func (a *App) Run(addr string) {
37+
fmt.Printf("Server running on %s \n", addr)
38+
log.Fatal(http.ListenAndServe(addr, a.Router))
39+
}
40+
41+
func (a *App) initializeRoutes() {
42+
api := a.Router.PathPrefix("/api/v1").Subrouter()
43+
api.HandleFunc("", a.getRequest).Methods(http.MethodGet)
44+
api.HandleFunc("", a.apiMakeDbRequest).Methods(http.MethodPost)
45+
api.HandleFunc("", a.notFound)
46+
api.HandleFunc("/user/{userID}/comment/{commentID}", a.withParams).Methods(http.MethodGet)
47+
48+
}
49+
50+
type QueryRequest struct {
51+
QueryString string `json:"query_string"`
52+
}
53+
54+
func (a *App) apiMakeDbRequest(w http.ResponseWriter, r *http.Request) {
55+
w.Header().Set("Content-Type", "application/json")
56+
reqBody, _ := ioutil.ReadAll(r.Body)
57+
58+
var queryrequest QueryRequest
59+
json.Unmarshal(reqBody, &queryrequest)
60+
fmt.Println(queryrequest)
61+
62+
response, err := do_db_query(queryrequest.QueryString)
63+
if err != nil {
64+
w.WriteHeader(http.StatusInternalServerError)
65+
w.Write([]byte(`{"message": "error"}`))
66+
}
67+
68+
fmt.Println(response)
69+
type RespObject struct {
70+
Data []interface{}
71+
}
72+
respObject := RespObject{response}
73+
data, err := json.Marshal(respObject)
74+
if err != nil {
75+
fmt.Println(err)
76+
}
77+
fmt.Println("", data)
78+
79+
w.Header().Set("Content-Type", "application/json")
80+
w.WriteHeader(http.StatusOK)
81+
w.Write(data)
82+
// var res map[string]interface{}
83+
// json.Marshal(&response, &res)
84+
85+
// w.Write([]byte(`{"message": "post called"}`))
86+
}
87+
88+
func (a *App) getRequest(w http.ResponseWriter, r *http.Request) {
89+
w.Header().Set("Content-Type", "application/json")
90+
w.WriteHeader(http.StatusOK)
91+
w.Write([]byte(`{"message": "get called"}`))
92+
}
93+
94+
func (a *App) withParams(w http.ResponseWriter, r *http.Request) {
95+
pathParams := mux.Vars(r)
96+
w.Header().Set("Content-Type", "application/json")
97+
98+
userID := -1
99+
var err error
100+
if val, ok := pathParams["userID"]; ok {
101+
userID, err = strconv.Atoi(val)
102+
if err != nil {
103+
w.WriteHeader(http.StatusInternalServerError)
104+
w.Write([]byte(`{"message": "need a number"}`))
105+
return
106+
}
107+
}
108+
109+
commentID := -1
110+
if val, ok := pathParams["commentID"]; ok {
111+
commentID, err = strconv.Atoi(val)
112+
if err != nil {
113+
w.WriteHeader(http.StatusInternalServerError)
114+
w.Write([]byte(`{"message": "need a number"}`))
115+
return
116+
}
117+
}
118+
119+
query := r.URL.Query()
120+
location := query.Get("location")
121+
// example query
122+
// http://127.0.0.1:8080/api/v1/user/23/comment/55?location=elsewhere
123+
w.Write([]byte(fmt.Sprintf(`{"userID": %d, "commentID": %d, "location": "%s" }`, userID, commentID, location)))
124+
}
125+
126+
func (a *App) notFound(w http.ResponseWriter, r *http.Request) {
127+
w.Header().Set("Content-Type", "application/json")
128+
w.WriteHeader(http.StatusNotFound)
129+
w.Write([]byte(`{"message": "not found"}`))
130+
}

main.go

Lines changed: 17 additions & 115 deletions
Original file line numberDiff line numberDiff line change
@@ -1,119 +1,21 @@
11
package main
22

3-
import (
4-
"encoding/json"
5-
"fmt"
6-
"io/ioutil"
7-
"log"
8-
"net/http"
9-
"strconv"
10-
11-
"github.com/gorilla/mux"
12-
_ "github.com/lib/pq"
13-
)
14-
15-
// func query_handler() {
16-
17-
// query_string := "SELECT \"ResId\", \"ResName\" FROM tbl_dk_resource"
18-
// query_string = "SELECT * FROM tbl_dk_res_category"
19-
// do_db_query(query_string)
20-
21-
// }
22-
23-
type QueryRequest struct {
24-
QueryString string `json:"query_string"`
25-
}
26-
27-
func notFound(w http.ResponseWriter, r *http.Request) {
28-
w.Header().Set("Content-Type", "application/json")
29-
w.WriteHeader(http.StatusNotFound)
30-
w.Write([]byte(`{"message": "not found"}`))
31-
}
32-
33-
func post(w http.ResponseWriter, r *http.Request) {
34-
w.Header().Set("Content-Type", "application/json")
35-
reqBody, _ := ioutil.ReadAll(r.Body)
36-
37-
var queryrequest QueryRequest
38-
json.Unmarshal(reqBody, &queryrequest)
39-
fmt.Println(queryrequest)
40-
41-
response, err := do_db_query(queryrequest.QueryString)
42-
if err != nil {
43-
w.WriteHeader(http.StatusInternalServerError)
44-
w.Write([]byte(`{"message": "error"}`))
45-
}
46-
47-
fmt.Println(response)
48-
type RespObject struct {
49-
Data []interface{}
50-
}
51-
respObject := RespObject{response}
52-
data, err := json.Marshal(respObject)
53-
if err != nil {
54-
fmt.Println(err)
55-
}
56-
fmt.Println("", data)
57-
58-
w.Header().Set("Content-Type", "application/json")
59-
w.WriteHeader(http.StatusOK)
60-
w.Write(data)
61-
// var res map[string]interface{}
62-
// json.Marshal(&response, &res)
63-
64-
// w.Write([]byte(`{"message": "post called"}`))
65-
}
66-
67-
func get(w http.ResponseWriter, r *http.Request) {
68-
w.Header().Set("Content-Type", "application/json")
69-
w.WriteHeader(http.StatusOK)
70-
w.Write([]byte(`{"message": "get called"}`))
71-
}
72-
73-
func withParams(w http.ResponseWriter, r *http.Request) {
74-
pathParams := mux.Vars(r)
75-
w.Header().Set("Content-Type", "application/json")
76-
77-
userID := -1
78-
var err error
79-
if val, ok := pathParams["userID"]; ok {
80-
userID, err = strconv.Atoi(val)
81-
if err != nil {
82-
w.WriteHeader(http.StatusInternalServerError)
83-
w.Write([]byte(`{"message": "need a number"}`))
84-
return
85-
}
86-
}
87-
88-
commentID := -1
89-
if val, ok := pathParams["commentID"]; ok {
90-
commentID, err = strconv.Atoi(val)
91-
if err != nil {
92-
w.WriteHeader(http.StatusInternalServerError)
93-
w.Write([]byte(`{"message": "need a number"}`))
94-
return
95-
}
96-
}
97-
98-
query := r.URL.Query()
99-
location := query.Get("location")
100-
// example query
101-
// http://127.0.0.1:8080/api/v1/user/23/comment/55?location=elsewhere
102-
w.Write([]byte(fmt.Sprintf(`{"userID": %d, "commentID": %d, "location": "%s" }`, userID, commentID, location)))
103-
}
104-
105-
func handleRequests() {
106-
r := mux.NewRouter()
107-
api := r.PathPrefix("/api/v1").Subrouter()
108-
api.HandleFunc("", get).Methods(http.MethodGet)
109-
api.HandleFunc("", post).Methods(http.MethodPost)
110-
api.HandleFunc("", notFound)
111-
api.HandleFunc("/user/{userID}/comment/{commentID}", withParams).Methods(http.MethodGet)
112-
113-
fmt.Println("Server started")
114-
log.Fatal(http.ListenAndServe(":8080", r))
115-
}
116-
1173
func main() {
118-
handleRequests()
4+
db_type := "postgres"
5+
db_user := "postgres"
6+
db_password := "123456"
7+
db_host := "localhost"
8+
db_database := "dbSapHasap"
9+
10+
a := App{}
11+
a.Initialize(
12+
db_type,
13+
db_user,
14+
db_password,
15+
db_host,
16+
db_database,
17+
)
18+
19+
a.Run(":8080")
20+
11921
}

0 commit comments

Comments
 (0)