Created
June 23, 2019 12:12
-
-
Save tonespy/6fcee5874e9dcf5fd3e21ea8d72e4bca to your computer and use it in GitHub Desktop.
Revisions
-
tonespy created this gist
Jun 23, 2019 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,64 @@ // ok represents types capable of validating // themselves. type ok interface { OK() error } // CreateUser :- Handler for creating a user // POST /user func createUser(w http.ResponseWriter, r *http.Request, params httprouter.Params) { var user models.User err := decode(r, &user) if err != nil { validationData := appError.Params{ "first_name": "required", "last_name": "required", "password": "required", "email": "required", } errResp := appError.NewAPIError(http.StatusBadRequest, "BAD_REQUEST", "Please provide valid user data.", validationData) appError.WriteErrorResponse(w, errResp) return } user.CreatedAt = time.Now().Local().String() user.UpdatedAt = time.Now().Local().String() user.ID = models.GenerateUserID() models.UserStore[strconv.Itoa(user.ID)] = user resp := response.GenericResponse(http.StatusCreated, "User Created Successfully.", user) response.WriteResponse(w, resp) } // GenerateUserRoutes :- Helper function for collating user routes func GenerateUserRoutes() []router.Route { // Create user setup createUserRoute := router.Route{ Name: "Create User", Method: "POST", Path: "/user", HandlerFunction: createUser, } // collate all routes routes := []router.Route{createUserRoute} return routes } // decode can be this simple to start with, but can be extended // later to support different formats and behaviours without // changing the interface. func decode(r *http.Request, v ok) error { if r.Body == nil { return errors.New("Invalid Body") } if err := json.NewDecoder(r.Body).Decode(v); err != nil { return err } return v.OK() }