modulepackage
1.0.0-RC2
Repository: https://github.com/thestephenstanton/hapi.git
Documentation: pkg.go.dev
# README
Go from this...
func (h handler) GetUsernameByID(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
userID := vars["id"]
username, err := h.repo.GetUsernameByID(userID)
if err != nil {
var errResponse errorResponse
var statusCode int
if errors.Is(sql.ErrNoRows, err) {
errResponse.Error = fmt.Sprintf("could not find username for user id '%s'", userID)
statusCode = http.StatusBadRequest
} else {
errResponse.Error = "request couldn't be processed, please try again later"
statusCode = http.StatusInternalServerError
}
bytes, err := json.Marshal(errResponse)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application-json")
w.WriteHeader(statusCode)
w.Write(bytes)
return
}
bytes, err := json.Marshal(usernameResponse{
Username: username,
})
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application-json")
w.WriteHeader(http.StatusOK)
w.Write(bytes)
}
TO THIS!
func (h handler) GetUsernameByID(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
userID := vars["id"]
username, err := h.repo.GetUsernameByID(userID)
if err != nil {
hapi.RespondError(w, err)
return
}
hapi.RespondOK(w, usernameResponse{
Username: username,
})
}
// Under construction...
# Packages
No description provided by the author
# Functions
GetQueryParam will return the first value for the key provided and true.
NewErrorResponse creates new ErrorResponse with an error message.NewErrorResponse.
Respond will marshal and return the payload to the client with a given status code.
RespondBadRequest will marshal the error payload and respond with a 400 status code.
RespondError will find if the error is a hapiError and if it is, get the message and set it to the error in the response.
RespondErrorFallback check if err is a type of hapiError.
RespondForbidden will marshal the error payload and respond with a 403 status code.
RespondInternalError will marshal the error payload and respond with a 500 status code.
RespondNotFound will marshal the error payload and respond with a 404 status code.
RespondOK will marshal the payload and respond with a 200 status code.
RespondTeapot will marshal the error payload and respond with a 418 status code.
RespondTooLarge will marshal the error payload and respond with a 413 status code.
RespondUnauthorized will marshal the error payload and respond with a 401 status code.
UnmarshalBody will unmarshal the request's body into the interface provided.
WithMaxSize will wrap the request in http.MaxBytesReader before trying to unmarshal.
# Variables
Config configs hapi.
# Structs
ErrorResponse is a standard error response that has an Error and a RawError.
# Type aliases
UnmarshalOption is an option with given the request for unmarshalling.