Skip to content

Commit a6a5c32

Browse files
committed
updated query
1 parent 247ead4 commit a6a5c32

File tree

1 file changed

+54
-9
lines changed

1 file changed

+54
-9
lines changed

main.go

Lines changed: 54 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
package main
22

33
import (
4+
"fmt"
45
"log"
56
"net/http"
7+
"strconv"
68

79
"github.com/gorilla/mux"
810
_ "github.com/lib/pq"
@@ -16,20 +18,63 @@ import (
1618

1719
// }
1820

19-
func home(w http.ResponseWriter, r *http.Request) {
21+
func notFound(w http.ResponseWriter, r *http.Request) {
2022
w.Header().Set("Content-Type", "application/json")
21-
switch r.Method {
22-
case "GET":
23-
w.WriteHeader(http.StatusOK)
24-
w.Write([]byte(`{"message": "get called"}`))
25-
case "POST":
26-
w.WriteHeader(http.StatusCreated)
27-
w.Write([]byte(`{"message": "post called"}`))
23+
w.WriteHeader(http.StatusNotFound)
24+
w.Write([]byte(`{"message": "not found"}`))
25+
}
26+
27+
func post(w http.ResponseWriter, r *http.Request) {
28+
w.Header().Set("Content-Type", "application/json")
29+
w.WriteHeader(http.StatusCreated)
30+
w.Write([]byte(`{"message": "post called"}`))
31+
}
32+
33+
func get(w http.ResponseWriter, r *http.Request) {
34+
w.Header().Set("Content-Type", "application/json")
35+
w.WriteHeader(http.StatusOK)
36+
w.Write([]byte(`{"message": "get called"}`))
37+
}
38+
39+
func withParams(w http.ResponseWriter, r *http.Request) {
40+
pathParams := mux.Vars(r)
41+
w.Header().Set("Content-Type", "application/json")
42+
43+
userID := -1
44+
var err error
45+
if val, ok := pathParams["userID"]; ok {
46+
userID, err = strconv.Atoi(val)
47+
if err != nil {
48+
w.WriteHeader(http.StatusInternalServerError)
49+
w.Write([]byte(`{"message": "need a number"}`))
50+
return
51+
}
2852
}
53+
54+
commentID := -1
55+
if val, ok := pathParams["commentID"]; ok {
56+
commentID, err = strconv.Atoi(val)
57+
if err != nil {
58+
w.WriteHeader(http.StatusInternalServerError)
59+
w.Write([]byte(`{"message": "need a number"}`))
60+
return
61+
}
62+
}
63+
64+
query := r.URL.Query()
65+
location := query.Get("location")
66+
// example query
67+
// http://127.0.0.1:8080/api/v1/user/23/comment/55?location=elsewhere
68+
w.Write([]byte(fmt.Sprintf(`{"userID": %d, "commentID": %d, "location": "%s" }`, userID, commentID, location)))
2969
}
3070

3171
func main() {
3272
r := mux.NewRouter()
33-
r.HandleFunc("/", home)
73+
api := r.PathPrefix("/api/v1").Subrouter()
74+
api.HandleFunc("", get).Methods(http.MethodGet)
75+
api.HandleFunc("", post).Methods(http.MethodPost)
76+
api.HandleFunc("", notFound)
77+
api.HandleFunc("/user/{userID}/comment/{commentID}", withParams).Methods(http.MethodGet)
78+
3479
log.Fatal(http.ListenAndServe(":8080", r))
3580
}

0 commit comments

Comments
 (0)