Skip to content

Commit 58aa88c

Browse files
author
Hamed Naeemaei
committed
Initialize http mini project
1 parent 80c7087 commit 58aa88c

File tree

8 files changed

+238
-0
lines changed

8 files changed

+238
-0
lines changed

17-Http/07-MiniProject/database/db.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package db
2+
3+
import "http-mini-project/models"
4+
5+
// set up a database dummy
6+
var (
7+
MovieDb = make(map[string]models.Movie)
8+
)

17-Http/07-MiniProject/go.mod

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module http-mini-project
2+
3+
go 1.18
Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
package handlers
2+
3+
import (
4+
"encoding/json"
5+
db "http-mini-project/database"
6+
"http-mini-project/models"
7+
"http-mini-project/utils"
8+
"net/http"
9+
)
10+
11+
type MovieHandler struct {
12+
}
13+
14+
var Users = map[string]models.Movie{}
15+
16+
func (u *MovieHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
17+
switch {
18+
19+
case r.Method == http.MethodGet && len(r.URL.Query().Get("id")) > 0:
20+
GetMovie(w, r)
21+
return
22+
case r.Method == http.MethodGet && len(r.URL.Query().Get("id")) == 0:
23+
GetMovies(w, r)
24+
return
25+
case r.Method == http.MethodPost:
26+
AddMovie(w, r)
27+
return
28+
case r.Method == http.MethodDelete:
29+
DeleteMovie(w, r)
30+
return
31+
}
32+
}
33+
34+
func GetMovies(w http.ResponseWriter, req *http.Request) {
35+
36+
if req.Method != "GET" {
37+
utils.SetResult(w, http.StatusMethodNotAllowed, nil, utils.ApiError{Id: "httpMethod", Message: "Not allowed"})
38+
return
39+
}
40+
41+
var movies []models.Movie
42+
43+
for _, movie := range db.MovieDb {
44+
movies = append(movies, movie)
45+
}
46+
47+
// parse the movie data into json format
48+
moviesJSON, err := json.Marshal(&movies)
49+
if err != nil {
50+
utils.SetResult(w, http.StatusInternalServerError, nil, utils.ApiError{Id: "jsonMarshal", Message: "Error parsing the movie data" + err.Error()})
51+
return
52+
}
53+
54+
utils.SetResult(w, http.StatusOK, moviesJSON, nil)
55+
}
56+
57+
func GetMovie(w http.ResponseWriter, req *http.Request) {
58+
59+
if req.Method != "GET" {
60+
utils.SetResult(w, http.StatusMethodNotAllowed, nil, utils.ApiError{Id: "httpMethod", Message: "Not allowed"})
61+
return
62+
}
63+
64+
if _, ok := req.URL.Query()["id"]; !ok {
65+
utils.SetResult(w, http.StatusBadRequest, nil, utils.ApiError{Id: "QueryStringMissed", Message: "This method requires the movie id"})
66+
return
67+
}
68+
69+
id := req.URL.Query()["id"][0]
70+
71+
movie, ok := db.MovieDb[id]
72+
if !ok {
73+
utils.SetResult(w, http.StatusNotFound, nil, nil)
74+
return
75+
}
76+
77+
// parse the movie data into json format
78+
movieJSON, err := json.Marshal(&movie)
79+
if err != nil {
80+
utils.SetResult(w, http.StatusInternalServerError, nil, utils.ApiError{Id: "jsonMarshal", Message: "Error parsing the movie data" + err.Error()})
81+
return
82+
}
83+
84+
utils.SetResult(w, http.StatusOK, movieJSON, nil)
85+
}
86+
87+
func AddMovie(w http.ResponseWriter, req *http.Request) {
88+
89+
if req.Method != "POST" {
90+
utils.SetResult(w, http.StatusMethodNotAllowed, nil, utils.ApiError{Id: "httpMethod", Message: "Not allowed"})
91+
return
92+
}
93+
94+
var movie models.Movie
95+
96+
payload := req.Body
97+
98+
defer req.Body.Close()
99+
// parse the movie data into json format
100+
err := json.NewDecoder(payload).Decode(&movie)
101+
if err != nil {
102+
utils.SetResult(w, http.StatusInternalServerError, nil, utils.ApiError{Id: "jsonMarshal", Message: "Error parsing the movie data" + err.Error()})
103+
return
104+
}
105+
106+
db.MovieDb[movie.ID] = movie
107+
108+
utils.SetResult(w, http.StatusCreated, nil, nil)
109+
}
110+
111+
func DeleteMovie(w http.ResponseWriter, req *http.Request) {
112+
113+
if req.Method != "DELETE" {
114+
utils.SetResult(w, http.StatusMethodNotAllowed, nil, utils.ApiError{Id: "httpMethod", Message: "Not allowed"})
115+
return
116+
}
117+
118+
if _, ok := req.URL.Query()["id"]; !ok {
119+
utils.SetResult(w, http.StatusBadRequest, nil, utils.ApiError{Id: "QueryStringMissed", Message: "This method requires the movie id"})
120+
return
121+
}
122+
123+
id := req.URL.Query()["id"][0]
124+
movie, ok := db.MovieDb[id]
125+
if !ok {
126+
utils.SetResult(w, http.StatusNotFound, nil, nil)
127+
return
128+
}
129+
// parse the movie data into json format
130+
movieJSON, err := json.Marshal(&movie)
131+
if err != nil {
132+
utils.SetResult(w, http.StatusInternalServerError, nil, utils.ApiError{Id: "jsonMarshal", Message: "Error parsing the movie data" + err.Error()})
133+
return
134+
}
135+
136+
utils.SetResult(w, http.StatusOK, nil, movieJSON)
137+
}

17-Http/07-MiniProject/main.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package main
2+
3+
import "http-mini-project/management"
4+
5+
func main() {
6+
management.Run()
7+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package management
2+
3+
import (
4+
"http-mini-project/handlers"
5+
"net/http"
6+
"time"
7+
)
8+
9+
func Run() {
10+
mux := http.NewServeMux()
11+
mux.Handle("/users/", &handlers.MovieHandler{})
12+
server := &http.Server{
13+
Addr: ":8080",
14+
ReadTimeout: time.Second * 10,
15+
WriteTimeout: time.Second * 10,
16+
Handler: mux,
17+
}
18+
19+
err := server.ListenAndServe()
20+
21+
if err != nil {
22+
panic(err)
23+
}
24+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package models
2+
3+
// Movie for modeling data dummy
4+
type Movie struct {
5+
ID string `json:"id"`
6+
Title string `json:"title"`
7+
Description string `json:"description"`
8+
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
package utils
2+
3+
type ApiError struct {
4+
Id string `json:"id"`
5+
Message string `json:"message"`
6+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package utils
2+
3+
import (
4+
"encoding/json"
5+
"net/http"
6+
)
7+
8+
type ApiResult struct {
9+
Success bool `json:"success"`
10+
Result interface{} `json:"result"`
11+
Error interface{} `json:"error"`
12+
}
13+
14+
func SetResult(w http.ResponseWriter, statusCode int, result interface{}, errorInfo interface{}) {
15+
16+
w.Header().Add("Web-Server", "NGINX")
17+
w.Header().Set("Content-Type", "application/json")
18+
19+
apiResult := &ApiResult{}
20+
if statusCode == http.StatusOK {
21+
apiResult.Success = true
22+
} else {
23+
apiResult.Success = false
24+
}
25+
26+
apiResult.Result = result
27+
28+
if errorInfo != nil {
29+
apiResult.Error = errorInfo
30+
}
31+
32+
jsonResponse, err := json.Marshal(apiResult)
33+
if err != nil {
34+
apiResult.Success = false
35+
apiResult.Error = err.Error()
36+
w.WriteHeader(http.StatusInternalServerError)
37+
}
38+
39+
w.WriteHeader(statusCode)
40+
_, err = w.Write(jsonResponse)
41+
if err != nil {
42+
panic(err)
43+
}
44+
45+
}

0 commit comments

Comments
 (0)