udemy-go-web-2/cmd/api/helpers.go

98 lines
2.0 KiB
Go
Raw Normal View History

package main
import (
"encoding/json"
"errors"
"io"
"net/http"
2024-08-13 11:58:33 +00:00
"golang.org/x/crypto/bcrypt"
)
func (app *application) readJSON(w http.ResponseWriter, r *http.Request, data interface{}) error {
maxBytes := 1048576
r.Body = http.MaxBytesReader(w, r.Body, int64(maxBytes))
dec := json.NewDecoder(r.Body)
err := dec.Decode(data)
if err != nil {
return err
}
// Make sure there is only one entry.
err = dec.Decode(&struct{}{})
if err != io.EOF {
return errors.New("body must only have a single JSON value")
}
return nil
}
2024-08-13 11:34:53 +00:00
// writeJSON writes arbitrary data out as JSON
func (app *application) writeJSON(
w http.ResponseWriter,
status int, data interface{},
headers ...http.Header,
) error {
out, err := json.MarshalIndent(data, "", "\t")
if err != nil {
return err
}
if len(headers) > 0 {
for k, v := range headers[0] {
w.Header()[k] = v
}
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
w.Write(out)
return nil
}
func (app *application) badRequest(w http.ResponseWriter, r *http.Request, err error) error {
2024-08-26 21:06:29 +00:00
var payload JSONResponse
2024-08-22 19:34:58 +00:00
payload.OK = false
payload.Message = err.Error()
out, err := json.MarshalIndent(payload, "", "\t")
if err != nil {
return err
}
w.Header().Set("Content-Type", "application/json")
2024-08-13 11:58:33 +00:00
w.WriteHeader(http.StatusBadGateway)
w.Write(out)
return nil
}
2024-08-13 11:47:56 +00:00
func (app *application) invalidCredentials(w http.ResponseWriter) error {
2024-08-26 21:06:29 +00:00
var payload JSONResponse
2024-08-22 19:34:58 +00:00
payload.OK = false
2024-08-13 11:47:56 +00:00
payload.Message = "invalid authentication credentials"
err := app.writeJSON(w, http.StatusUnauthorized, payload)
if err != nil {
return err
}
return nil
}
2024-08-13 11:58:33 +00:00
func (app *application) passwordMatches(hash, password string) (bool, error) {
2024-08-13 12:12:40 +00:00
app.errorLog.Println(hash, password)
2024-08-13 11:58:33 +00:00
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
if err != nil {
switch {
case errors.Is(err, bcrypt.ErrMismatchedHashAndPassword):
return false, nil
default:
return false, err
}
}
return true, nil
}