-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
201 lines (181 loc) · 5.81 KB
/
server.go
File metadata and controls
201 lines (181 loc) · 5.81 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
package main
import (
"encoding/json"
"fmt"
"net"
"net/http"
"strconv"
"strings"
"time"
"github.com/alexliesenfeld/health"
"github.com/coma-toast/ResumAPI/internal/utils"
"github.com/coma-toast/ResumAPI/pkg/candidate"
"github.com/gorilla/mux"
)
type API struct {
instances APIInstances
conf *utils.Config
env *Env
}
type APIInstances struct {
notificationInstance NotificationInstance
candidateDataInstance CandidateDataInstance
}
type JSONResponse struct {
OK bool `json:"ok"`
Error string `json:"error"`
Data string `json:"data,omitempty"`
}
func (api API) RunAPI() {
checker := health.NewChecker(
health.WithCacheDuration(1*time.Second),
health.WithTimeout(10*time.Second),
)
r := mux.NewRouter()
r.HandleFunc("/", api.LandingHandler).Methods(http.MethodGet)
r.HandleFunc("/", api.AddCandidateHandler).Methods(http.MethodPost)
r.HandleFunc("/{id}/{section}", api.CandidateHandler)
r.HandleFunc("/{id}", api.SetCandidateHandler).Methods(http.MethodPost)
r.HandleFunc("/ping", api.PingHandler)
r.HandleFunc("/health", health.NewHandler(checker))
r.HandleFunc("/reset", api.ResetHandler)
r.Use(api.notificationMiddleware)
api.env.Logger.LogError("", "", "api handler failed", http.ListenAndServe(fmt.Sprintf(":%s", api.conf.Port), r))
}
func (api *API) notificationMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ip, err := api.getIP(r)
if err != nil {
api.env.Logger.LogError("", "", "unable to get IP", err)
}
message := fmt.Sprintf("API called: %s from %s", r.URL.Path, ip)
api.env.Logger.LogInfo("API called", r.URL.Path, "", nil)
if r.URL.Path != "/health" {
api.instances.notificationInstance.SendMessage("ResumAPI", message)
}
next.ServeHTTP(w, r)
})
}
func (api *API) respondWithJSON(w http.ResponseWriter, code int, payload interface{}) {
response, _ := json.Marshal(payload)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(response)
}
func (api *API) respondWithError(w http.ResponseWriter, code int, message string) {
api.respondWithJSON(w, code, JSONResponse{Error: message, OK: false})
}
// PingHandler is just a quick test to ensure api calls are working.
func (api *API) PingHandler(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
api.env.Logger.LogDebug("Request sent to /api/ping")
w.Write([]byte("Pong\n"))
}
func (api *API) LandingHandler(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
http.Redirect(w, r, api.conf.LandingPage, http.StatusMovedPermanently)
}
func (api *API) CandidateHandler(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
vars := mux.Vars(r)
id, err := strconv.Atoi(vars["id"])
if err != nil {
api.env.Logger.LogError("", "", "error getting candidate ID", err)
api.respondWithError(w, http.StatusBadRequest, "No candidates found.")
return
}
candidate := api.instances.candidateDataInstance.GetCandidateByID(id)
var data interface{}
switch section := vars["section"]; section {
case "contact":
data = candidate.Contact
case "experience":
data = candidate.Experience
case "projects":
data = candidate.Projects
case "dev-env":
data = candidate.DevEnvs
case "hobbies":
data = candidate.Hobbies
}
api.respondWithJSON(w, 200, data)
}
func (api *API) SetCandidateHandler(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
vars := mux.Vars(r)
id, err := strconv.Atoi(vars["id"])
if err != nil {
api.env.Logger.LogError("", "", "error converting string to int", err)
api.respondWithError(w, http.StatusBadRequest, "user id error")
return
}
var candidate candidate.Candidate
err = json.NewDecoder(r.Body).Decode(&candidate)
if err != nil {
api.env.Logger.LogError("", "", "error decoding json", err)
api.respondWithError(w, http.StatusBadRequest, "error setting data")
return
}
err = api.instances.candidateDataInstance.SetCandidate(id, candidate)
if err != nil {
api.respondWithError(w, http.StatusBadRequest, "error adding user")
return
}
api.respondWithJSON(w, http.StatusOK, fmt.Sprintf("user %d updated successfully", id))
}
func (api *API) AddCandidateHandler(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
var candidate candidate.Candidate
err := json.NewDecoder(r.Body).Decode(&candidate)
if err != nil {
api.env.Logger.LogError("", "", "error decoding json", err)
api.respondWithError(w, http.StatusBadRequest, "error setting data")
return
}
id, err := api.instances.candidateDataInstance.AddCandidate(candidate)
if err != nil {
api.respondWithError(w, http.StatusBadRequest, "error adding user")
return
}
api.respondWithJSON(w, http.StatusOK, fmt.Sprintf("user %d added successfully", id))
}
func (api *API) ResetHandler(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
candidate := candidate.Candidate{
// * Put your custom data here - you can use personalData.go to build and object to copy and paste.
// ! do not commit any changes added here
}
id, err := api.instances.candidateDataInstance.AddCandidate(candidate)
if err != nil {
api.respondWithError(w, http.StatusBadRequest, "error adding user")
return
}
api.respondWithJSON(w, http.StatusOK, fmt.Sprintf("user %d added successfully", id))
}
func (api *API) getIP(r *http.Request) (string, error) {
//Get IP from the X-REAL-IP header
ip := r.Header.Get("X-REAL-IP")
netIP := net.ParseIP(ip)
if netIP != nil {
return ip, nil
}
//Get IP from X-FORWARDED-FOR header
ips := r.Header.Get("X-FORWARDED-FOR")
splitIps := strings.Split(ips, ",")
for _, ip := range splitIps {
netIP := net.ParseIP(ip)
if netIP != nil {
return ip, nil
}
}
//Get IP from RemoteAddr
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return "", err
}
netIP = net.ParseIP(ip)
if netIP != nil {
return ip, nil
}
return "", fmt.Errorf("no valid ip found")
}