package server import ( "JISQueueing/db" "encoding/json" nhttp "net/http" ) type errorResponse struct { Success bool `json:"success"` Reason interface{} `json:"reason"` } type successResponse struct { Success bool `json:"success"` Data interface{} `json:"data"` } //InvalidUserInput : A helper function that tells the client that some request validation had failed. (Malformed requests) func InvalidUserInput(w nhttp.ResponseWriter, r *nhttp.Request) { writeJSONResponse(w, nhttp.StatusBadRequest, "Your request had failed checks.") } //Unauthorized : A helper function that tells the client that they either forgot to provide `token` or it was invalid. //This function is also used in `/api/login` to tell the client that the user/password combination is incorrect. func Unauthorized(w nhttp.ResponseWriter, r *nhttp.Request) { writeJSONResponse(w, nhttp.StatusUnauthorized, "Identifying details not provided or invalid.") } //NotFound : A helper function that tells the client that the API endpoint they requested does not exist. func NotFound(w nhttp.ResponseWriter, r *nhttp.Request) { writeJSONResponse(w, nhttp.StatusNotFound, "The API endpoint was not found.") } //InternalServerError : A helper function that tells the client that the server had encountered an error processing their request. func InternalServerError(w nhttp.ResponseWriter, r *nhttp.Request) { writeJSONResponse(w, nhttp.StatusInternalServerError, "An internal server error occurred.") } //writeJSONResponse : A helper function that writes the given message into the standard response the client expects. func writeJSONResponse(w nhttp.ResponseWriter, statusCode int, message interface{}) { w.Header().Set("Content-Type", "application/json") var toWrite interface{} if statusCode == nhttp.StatusOK { toWrite = successResponse{ Success: true, Data: message, } } else { w.WriteHeader(statusCode) toWrite = errorResponse{ Success: false, Reason: message, } } result, _ := json.Marshal(toWrite) w.Write(result) } //handleToken : A helper function that checks if the token provided by the client is valid. //Returns if it is valid and sends the Unauthorized message if it isn't. func handleToken(w nhttp.ResponseWriter, r *nhttp.Request) bool { err := r.ParseForm() if err != nil { InvalidUserInput(w, r) return false } if db.VerifyToken(r.Form.Get("token")) { return true } Unauthorized(w, r) return false }