Skip to content

Instantly share code, notes, and snippets.

@tonespy
Created June 23, 2019 12:12
Show Gist options
  • Select an option

  • Save tonespy/6fcee5874e9dcf5fd3e21ea8d72e4bca to your computer and use it in GitHub Desktop.

Select an option

Save tonespy/6fcee5874e9dcf5fd3e21ea8d72e4bca to your computer and use it in GitHub Desktop.

Revisions

  1. tonespy created this gist Jun 23, 2019.
    64 changes: 64 additions & 0 deletions user_api.go
    Original 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()
    }