udemy-go-microservices/broker-service/cmd/api/handlers.go

103 lines
2.2 KiB
Go

package main
import (
"bytes"
"encoding/json"
"errors"
"log"
"net/http"
)
type RequestPayload struct {
Action string `string:"action"`
Auth AuthPayload ` json:"auth,omitempty"`
}
type AuthPayload struct {
Email string `json:"email"`
Password string `json:"password"`
}
func (app *Config) Broker(w http.ResponseWriter, r *http.Request) {
payload := jsonResponse{
Error: false,
Message: "Hit the broker",
}
app.writeJSON(w, http.StatusOK, payload)
}
func (app *Config) HandleSubmission(w http.ResponseWriter, r *http.Request) {
var requestPayload RequestPayload
err := app.readJSON(w, r, &requestPayload)
if err != nil {
app.errorJSON(w, err, http.StatusBadRequest)
return
}
switch requestPayload.Action {
case "auth":
app.authenticate(w, requestPayload.Auth)
default:
app.errorJSON(w, errors.New("unknown action"))
}
}
func (app *Config) authenticate(w http.ResponseWriter, a AuthPayload) {
// create some json we'll send to the auth microservice
authPayload, err := json.MarshalIndent(a, "", "\t")
if err != nil {
app.errorJSON(w, err, http.StatusBadRequest)
return
}
// call the service
req, err := http.NewRequest(
"POST",
"http://authentication-service:4000/authenticate",
bytes.NewBuffer(authPayload),
)
if err != nil {
app.errorJSON(w, err, http.StatusBadRequest)
return
}
req.Header.Add("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
app.errorJSON(w, err, http.StatusInternalServerError)
return
}
defer resp.Body.Close()
log.Println(resp.Body)
// make sure we get back the correct status code
if resp.StatusCode != http.StatusAccepted {
app.errorJSON(w, errors.New("invalid credentials"))
return
}
// create a variable we'll read resp.Body into
var respPayload jsonResponse
err = json.NewDecoder(resp.Body).Decode(&respPayload)
if err != nil {
app.errorJSON(w, err, http.StatusBadRequest)
return
}
if respPayload.Error {
app.errorJSON(w, errors.New(respPayload.Message), http.StatusUnauthorized)
return
}
var payload jsonResponse
payload.Error = false
payload.Message = "Authenticated!"
payload.Data = respPayload.Data
app.writeJSON(w, http.StatusOK, payload)
}