Skip to content

Commit

Permalink
Merge pull request #138 from PacoVK/refactor_for_tests
Browse files Browse the repository at this point in the history
Refactor for tests
  • Loading branch information
PacoVK authored Aug 31, 2022
2 parents fe32927 + 365c115 commit 8c4a7bd
Show file tree
Hide file tree
Showing 11 changed files with 10,514 additions and 103 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ on:
- cron: '0 05 * * *'
push:
branches:
- '**'
- main
tags:
- 'v*.*.*'
pull_request:
Expand Down
22 changes: 22 additions & 0 deletions .github/workflows/server.test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
name: Server tests
on: push

jobs:
unit:
runs-on: ubuntu-latest
container: golang
services:
localstack:
image: localstack/localstack:1.0.4
env:
SERVICES: sqs
EXTRA_CORS_ALLOWED_ORIGINS: "*"
env:
AWS_ACCESS_KEY_ID: fake
AWS_SECRET_ACCESS_KEY: fake
SQS_ENDPOINT_URL: http://localstack:4566
steps:
- uses: actions/checkout@v3
- name: test
working-directory: server
run: go test -v ./...
58 changes: 12 additions & 46 deletions server/aws/sqsClient.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,16 @@ func getQueueAttributes(queueUrl *string) (*sqs.GetQueueAttributesOutput, error)
}

func ListQueues() []types.SqsQueue {
var queues = []types.SqsQueue{}
var queues = make([]types.SqsQueue, 0)
result, err := getQueues()
if err != nil {
log.Println("Got an error retrieving queue URLs:")
log.Println(err)
log.Printf("Got an error retrieving queue URLs: %v", err.Error())
return queues
}
for _, url := range result.QueueUrls {
attributes, err := getQueueAttributes(&url)
if err != nil {
log.Println("Got an error retrieving queue Attributes:")
log.Println(err)
log.Printf("Got an error retrieving queue Attributes: %v", err.Error())
return queues
}
arnParts := strings.Split(attributes.Attributes["QueueArn"], ":")
Expand All @@ -56,7 +54,7 @@ func receiveMessages(queueUrl *string) (*sqs.ReceiveMessageOutput, error) {
}

func GetMessages(queueUrl string) ([]types.SqsMessage, error) {
var sqsMessages = []types.SqsMessage{}
var sqsMessages = make([]types.SqsMessage, 0)
messages, err := receiveMessages(&queueUrl)
if err != nil {
return nil, err
Expand All @@ -71,59 +69,27 @@ func GetMessages(queueUrl string) ([]types.SqsMessage, error) {
return sqsMessages, nil
}

func purgeQueue(queueUrl *string) (*sqs.PurgeQueueOutput, error) {
func PurgeQueue(queueUrl string) (*sqs.PurgeQueueOutput, error) {
return sqsClient.PurgeQueue(context.TODO(), &sqs.PurgeQueueInput{
QueueUrl: queueUrl,
QueueUrl: &queueUrl,
})
}

func PurgeQueue(queueUrl string) error {
_, err := purgeQueue(&queueUrl)
if err != nil {
return err
}
return nil
}

func deleteQueue(queueUrl *string) (*sqs.DeleteQueueOutput, error) {
func DeleteQueue(queueUrl string) (*sqs.DeleteQueueOutput, error) {
return sqsClient.DeleteQueue(context.TODO(), &sqs.DeleteQueueInput{
QueueUrl: queueUrl,
QueueUrl: &queueUrl,
})
}

func DeleteQueue(queueUrl string) error {
_, err := deleteQueue(&queueUrl)
if err != nil {
return err
}
return nil
}

func createQueue(queueName *string) (*sqs.CreateQueueOutput, error) {
func CreateQueue(queueName string) (*sqs.CreateQueueOutput, error) {
return sqsClient.CreateQueue(context.TODO(), &sqs.CreateQueueInput{
QueueName: queueName,
QueueName: &queueName,
})
}

func CreateQueue(queueName string) error {
_, err := createQueue(&queueName)
if err != nil {
return err
}
return nil
}

func sendMessage(queueUrl *string, sqsMessage *types.SqsMessage) (*sqs.SendMessageOutput, error) {
func SendMessage(queueUrl string, sqsMessage types.SqsMessage) (*sqs.SendMessageOutput, error) {
return sqsClient.SendMessage(context.TODO(), &sqs.SendMessageInput{
QueueUrl: queueUrl,
QueueUrl: &queueUrl,
MessageBody: &sqsMessage.MessageBody,
})
}

func SendMessage(queueUrl string, sqsMessage types.SqsMessage) error {
_, err := sendMessage(&queueUrl, &sqsMessage)
if err != nil {
return err
}
return nil
}
10 changes: 10 additions & 0 deletions server/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
version: '3.7'
services:

localstack:
image: localstack/localstack
ports:
- "4566:4566"
environment:
SERVICES: sqs
EXTRA_CORS_ALLOWED_ORIGINS: "*"
2 changes: 1 addition & 1 deletion server/go.mod
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module github.com/pacoVK

go 1.18
go 1.19

require (
github.com/aws/aws-sdk-go-v2 v1.16.11
Expand Down
92 changes: 42 additions & 50 deletions server/handler/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,81 +2,73 @@ package handler

import (
"encoding/json"
"errors"
"github.com/pacoVK/aws"
"github.com/gorilla/mux"
"github.com/pacoVK/aws/types"
"io/ioutil"
"io"
"log"
"net/http"
)

func WebsiteHandler() http.Handler {
return http.FileServer(http.Dir("../public"))
type Handler struct {
Route func(r *mux.Route)
Func http.HandlerFunc
}

func ListQueuesHandler(w http.ResponseWriter, r *http.Request) {
queues := aws.ListQueues()
respondJSON(w, http.StatusOK, queues)
type Response struct {
Payload interface{} `json:"payload"`
StatusCode int `json:"statusCode"`
Error error `json:"error"`
}

func SQSHandler(w http.ResponseWriter, r *http.Request) {
payload := unpackPayload(r)
switch payload.Action {
case "CreateQueue":
log.Printf("Creating queue [%v]", payload.SqsQueue.QueueName)
checkErrorAndRespond(aws.CreateQueue(payload.SqsQueue.QueueName), &w)
case "SendMessage":
log.Printf("Send message to queue [%v]", payload.SqsQueue.QueueName)
checkErrorAndRespond(aws.SendMessage(payload.SqsQueue.QueueUrl, payload.SqsMessage), &w)
case "DeleteQueue":
log.Printf("Deleting queue [%v]", payload.SqsQueue.QueueName)
checkErrorAndRespond(aws.DeleteQueue(payload.SqsQueue.QueueUrl), &w)
case "PurgeQueue":
log.Printf("Purging queue [%v]", payload.SqsQueue.QueueName)
checkErrorAndRespond(aws.PurgeQueue(payload.SqsQueue.QueueUrl), &w)
case "GetMessages":
messages, err := aws.GetMessages(payload.SqsQueue.QueueUrl)
if err != nil {
respondError(w, http.StatusBadRequest, err.Error())
} else {
respondJSON(w, http.StatusOK, messages)
}
default:
log.Printf("Unsupported action provided [%v]", payload.Action)
respondError(w, http.StatusBadRequest, errors.New("unsupported method").Error())
}
func (h Handler) AddRoute(r *mux.Router) {
h.Route(r.NewRoute().HandlerFunc(h.Func))
}

func unpackPayload(r *http.Request) *types.Request {
func unpackRequestPayload(r io.ReadCloser) *types.Request {
data := types.Request{}
jsonBlob, err := ioutil.ReadAll(r.Body)
jsonBlob, err := io.ReadAll(r)
if err != nil {
log.Fatal(err.Error())
}
json.Unmarshal(jsonBlob, &data)
return &data
}

func respondJSON(w http.ResponseWriter, status int, payload interface{}) {
response, err := json.Marshal(payload)
func unpackResponsePayload(r io.ReadCloser) []types.SqsMessage {
data := make([]types.SqsMessage, 0)
jsonBlob, err := io.ReadAll(r)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
log.Fatal(err.Error())
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
w.Write(response)
json.Unmarshal(jsonBlob, &data)
return data
}

func respondError(w http.ResponseWriter, code int, message string) {
respondJSON(w, code, map[string]string{"error": message})
func respondJSON(w http.ResponseWriter, res Response) {
var response, err = json.Marshal(res.Payload)
if err != nil {
respondJSON(w, Response{
StatusCode: http.StatusInternalServerError,
Error: err,
})
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(res.StatusCode)
w.Write(response)
}

func checkErrorAndRespond(err error, w *http.ResponseWriter) {
if err != nil {
respondError(*w, http.StatusBadRequest, err.Error())
func checkForErrorAndRespondJSON(w *http.ResponseWriter, res Response) {
if res.Error != nil {
respondJSON(*w, Response{
Payload: nil,
StatusCode: http.StatusBadRequest,
Error: res.Error,
})
} else {
respondJSON(*w, http.StatusOK, nil)
respondJSON(*w, Response{
Payload: res.Payload,
StatusCode: http.StatusOK,
Error: nil,
})
}
}
75 changes: 75 additions & 0 deletions server/handler/sqsHandler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package handler

import (
"fmt"
"github.com/gorilla/mux"
"github.com/pacoVK/aws"
"log"
"net/http"
)

func WebsiteHandler() http.Handler {
return http.FileServer(http.Dir("../public"))
}

func SQSHandler() Handler {
return Handler{
Route: func(r *mux.Route) {
r.Methods("GET", "POST").Path("/sqs")
},
Func: func(writer http.ResponseWriter, request *http.Request) {
if request.Method == http.MethodGet {
queues := aws.ListQueues()
respondJSON(writer, Response{
Payload: queues,
StatusCode: http.StatusOK,
})
} else {
payload := unpackRequestPayload(request.Body)
switch payload.Action {
case "CreateQueue":
log.Printf("Creating queue [%v]", payload.SqsQueue.QueueName)
_, err := aws.CreateQueue(payload.SqsQueue.QueueName)
checkForErrorAndRespondJSON(&writer, Response{
Payload: nil,
Error: err,
})
case "SendMessage":
log.Printf("Send message to queue [%v]", payload.SqsQueue.QueueName)
_, err := aws.SendMessage(payload.SqsQueue.QueueUrl, payload.SqsMessage)
checkForErrorAndRespondJSON(&writer, Response{
Payload: nil,
Error: err,
})
case "DeleteQueue":
log.Printf("Deleting queue [%v]", payload.SqsQueue.QueueName)
_, err := aws.DeleteQueue(payload.SqsQueue.QueueUrl)
checkForErrorAndRespondJSON(&writer, Response{
Payload: nil,
Error: err,
})
case "PurgeQueue":
log.Printf("Purging queue [%v]", payload.SqsQueue.QueueName)
_, err := aws.PurgeQueue(payload.SqsQueue.QueueUrl)
checkForErrorAndRespondJSON(&writer, Response{
Payload: nil,
Error: err,
})
case "GetMessages":
messages, err := aws.GetMessages(payload.SqsQueue.QueueUrl)
checkForErrorAndRespondJSON(&writer, Response{
Payload: messages,
Error: err,
})
default:
log.Printf("Unsupported action provided [%v]", payload.Action)
respondJSON(writer, Response{
Payload: fmt.Sprintf("Unsupported action provided [%v]", payload.Action),
StatusCode: http.StatusBadRequest,
})
}
}
},
}

}
Loading

0 comments on commit 8c4a7bd

Please sign in to comment.