diff --git a/.gitignore b/.gitignore index 1abb349..542ee36 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,36 @@ -**.tfvars -**.tfstate -**.tfstate.* -**/.terraform/ \ No newline at end of file +# ===== Terraform ===== +.terraform/ +terraform.tfstate +terraform.tfstate.* +*.tfvars +*.tfplan +.terraform.lock.hcl + +# ===== AWS Credentials ===== +*.pem +*.key +*.env +.aws/ +credentials/ +config/ + +# ===== Go Binaries ===== +main +*.exe +*.out + +# ===== Docker / Build Cache ===== +*.log +*.tmp +docker-compose.override.yml + +# ===== IDE / System Files ===== +.DS_Store +.idea/ +.vscode/ +*.swp + +# ===== Misc ===== +*.zip +*.tar +*.gz diff --git a/README.MD b/README.MD index c53bafb..691b88f 100644 --- a/README.MD +++ b/README.MD @@ -1,3 +1,12 @@ +# Distributed System – Product API + +This project deploys a simple **Go-based REST API** to AWS ECS using **Terraform** and **Docker**. +The service exposes endpoints to retrieve and manage product data. + +These instructions explain exactly how to deploy and test the system on **any machine**. + + + ## Instructions ### Prepare Credentials @@ -20,6 +29,24 @@ terraform init terraform apply -auto-approve ``` +Once complete, Terraform will output: +ecs_cluster_name +ecs_service_name + +### Step 3: Build and Push Docker Image +``` +cd src +docker buildx build --platform linux/amd64 \ + -t :latest \ + --push . +``` + +Then redeploy by re-running: +``` +cd ../terraform +terraform apply -auto-approve +``` + ### Send Requests Make sure you are in terraform folder @@ -42,11 +69,12 @@ aws ec2 describe-network-interfaces \ --output text ``` -Send some requests: +### Test API Endpoints ``` -curl http://:8080/albums +curl http://:8080/products ``` + ## Clean Up ``` terraform destroy -auto-approve diff --git a/__pycache__/locustfile.cpython-39.pyc b/__pycache__/locustfile.cpython-39.pyc new file mode 100644 index 0000000..dceaf08 Binary files /dev/null and b/__pycache__/locustfile.cpython-39.pyc differ diff --git a/demo.docx b/demo.docx new file mode 100644 index 0000000..4fdc90b Binary files /dev/null and b/demo.docx differ diff --git a/locustfile.py b/locustfile.py new file mode 100644 index 0000000..024ac31 --- /dev/null +++ b/locustfile.py @@ -0,0 +1,52 @@ +# locustfile.py +import random +from locust import HttpUser, FastHttpUser, task, between + +PRODUCT_ID_MIN = 1 +PRODUCT_ID_MAX = 1000 + +def make_payload(pid): + return { + "product_id": pid, + "sku": f"SKU-{pid:04d}", + "manufacturer": "Acme", + "category_id": 10, + "weight": 100 + (pid % 50), + "some_other_id": 9 + } + +# ------------------------- +# Regular HTTP client +# ------------------------- +class StoreUser(HttpUser): + wait_time = between(0.05, 0.2) + + @task(5) + def get_product(self): + pid = random.randint(PRODUCT_ID_MIN, PRODUCT_ID_MAX) + self.client.get(f"/products/{pid}", name="/products/:id") + + @task(1) + def post_details(self): + pid = random.randint(PRODUCT_ID_MIN, PRODUCT_ID_MAX) + payload = make_payload(pid) + self.client.post(f"/products/{pid}/details", + json=payload, name="/products/:id/details") + +# ------------------------- +# FastHTTP client +# ------------------------- +class StoreUserFast(FastHttpUser): + wait_time = between(0.05, 0.2) + + @task(5) + def get_product(self): + pid = random.randint(PRODUCT_ID_MIN, PRODUCT_ID_MAX) + self.client.get(f"/products/{pid}", name="/products/:id") + + @task(1) + def post_details(self): + pid = random.randint(PRODUCT_ID_MIN, PRODUCT_ID_MAX) + payload = make_payload(pid) + self.client.post(f"/products/{pid}/details", + json=payload, name="/products/:id/details") diff --git a/src/Dockerfile b/src/Dockerfile index addfed4..3d3bafb 100644 --- a/src/Dockerfile +++ b/src/Dockerfile @@ -1,20 +1,27 @@ -FROM golang:1.24-alpine AS build -RUN apk add --no-cache git +FROM golang:1.25-alpine AS builder -WORKDIR /src +# Set working directory +WORKDIR /app + +# Copy go mod and sum, then download dependencies COPY go.mod go.sum ./ -RUN go mod download +RUN go mod tidy +# Copy all source code COPY . . -# disable cgo, target linux, static link -RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \ - go build -ldflags="-s -w" -o server . -FROM alpine:latest -RUN apk add --no-cache ca-certificates +# ✅ Build Linux amd64 binary (for ECS) +RUN GOOS=linux GOARCH=amd64 go build -o main . + +# Second, minimal runtime image +FROM alpine:3.19 WORKDIR /app -COPY --from=build /src/server . +COPY --from=builder /app/main . + +# Ensure binary is executable +RUN chmod +x main EXPOSE 8080 -ENTRYPOINT ["./server"] \ No newline at end of file +CMD ["./main"] + diff --git a/src/go.mod b/src/go.mod index 586cd83..f034eea 100644 --- a/src/go.mod +++ b/src/go.mod @@ -1,34 +1,5 @@ -module text/main +module product-api -go 1.24.0 +go 1.25.1 -require github.com/gin-gonic/gin v1.10.1 - -require ( - github.com/bytedance/sonic v1.11.6 // indirect - github.com/bytedance/sonic/loader v0.1.1 // indirect - github.com/cloudwego/base64x v0.1.4 // indirect - github.com/cloudwego/iasm v0.2.0 // indirect - github.com/gabriel-vasile/mimetype v1.4.3 // indirect - github.com/gin-contrib/sse v0.1.0 // indirect - github.com/go-playground/locales v0.14.1 // indirect - github.com/go-playground/universal-translator v0.18.1 // indirect - github.com/go-playground/validator/v10 v10.20.0 // indirect - github.com/goccy/go-json v0.10.2 // indirect - github.com/json-iterator/go v1.1.12 // indirect - github.com/klauspost/cpuid/v2 v2.2.7 // indirect - github.com/leodido/go-urn v1.4.0 // indirect - github.com/mattn/go-isatty v0.0.20 // indirect - github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect - github.com/modern-go/reflect2 v1.0.2 // indirect - github.com/pelletier/go-toml/v2 v2.2.2 // indirect - github.com/twitchyliquid64/golang-asm v0.15.1 // indirect - github.com/ugorji/go/codec v1.2.12 // indirect - golang.org/x/arch v0.8.0 // indirect - golang.org/x/crypto v0.23.0 // indirect - golang.org/x/net v0.25.0 // indirect - golang.org/x/sys v0.20.0 // indirect - golang.org/x/text v0.15.0 // indirect - google.golang.org/protobuf v1.34.1 // indirect - gopkg.in/yaml.v3 v3.0.1 // indirect -) +require github.com/gorilla/mux v1.8.1 diff --git a/src/go.sum b/src/go.sum index 0397106..7128337 100644 --- a/src/go.sum +++ b/src/go.sum @@ -1,89 +1,2 @@ -github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0= -github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4= -github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM= -github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= -github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y= -github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w= -github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg= -github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0= -github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk= -github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= -github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= -github.com/gin-gonic/gin v1.10.1 h1:T0ujvqyCSqRopADpgPgiTT63DUQVSfojyME59Ei63pQ= -github.com/gin-gonic/gin v1.10.1/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y= -github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= -github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= -github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= -github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= -github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= -github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= -github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8= -github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM= -github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= -github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= -github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= -github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= -github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= -github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= -github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM= -github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= -github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= -github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= -github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= -github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= -github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= -github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= -github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= -github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= -github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM= -github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= -github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= -github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= -github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= -github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= -github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= -github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= -github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE= -github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= -golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= -golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc= -golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= -golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI= -golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= -golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac= -golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= -golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y= -golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk= -golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg= -google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= -gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50= -rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= +github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= +github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= diff --git a/src/main.go b/src/main.go index 6c3ee7e..d3809be 100644 --- a/src/main.go +++ b/src/main.go @@ -1,67 +1,174 @@ package main import ( - "net/http" + "encoding/json" + "fmt" + "net/http" + "os" + "strconv" - "github.com/gin-gonic/gin" + "github.com/gorilla/mux" ) -// album represents data about a record album. -type album struct { - ID string `json:"id"` - Title string `json:"title"` - Artist string `json:"artist"` - Price float64 `json:"price"` +// find Product and errorResponses schema from api.yaml line 419 - 485 +type Product struct { + ProductID int `json:"product_id"` + SKU string `json:"sku"` + Manufacturer string `json:"manufacturer"` + CategoryID int `json:"category_id"` + Weight int `json:"weight"` + SomeOtherID int `json:"some_other_id"` } -// albums slice to seed record album data. -var albums = []album{ - {ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99}, - {ID: "2", Title: "Jeru", Artist: "Gerry Mulligan", Price: 17.99}, - {ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99}, +type ErrorResponse struct { + Error string `json:"error"` + Message string `json:"message"` + Details string `json:"details,omitempty"` } -func main() { - router := gin.Default() - router.GET("/albums", getAlbums) - router.GET("/albums/:id", getAlbumByID) - router.POST("/albums", postAlbums) - - router.Run(":8080") +// helper to send JSON error responses +func writeError(w http.ResponseWriter, status int, errType, message, details string) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + json.NewEncoder(w).Encode(ErrorResponse{ + Error: errType, + Message: message, + Details: details, + }) } -// getAlbums responds with the list of all albums as JSON. -func getAlbums(c *gin.Context) { - c.IndentedJSON(http.StatusOK, albums) +// in-memory store +var products = make(map[int]Product) + +// POST with 404 product not found error implies that the product must already exist in the system before we can add or update its details. +// other words, I write the code as the endpoint should update details for existing products, and return a 404 error if the specified product ID is not found in the store. + +func createOrUpdateProduct(w http.ResponseWriter, r *http.Request) { + defer func() { + if rec := recover(); rec != nil { + writeError(w, http.StatusInternalServerError, + "INTERNAL_SERVER_ERROR", + "An unexpected error occurred", + fmt.Sprintf("%v", rec)) + } + }() // this is to add the 500 error response + + //We use mux because it allows us to easily define REST-style endpoints with path variables like /products/{productId}. + //The call mux.Vars(r) extracts those variables into a map so we can access and use them in our handler. + vars := mux.Vars(r) + id, err := strconv.Atoi(vars["id"]) + if err != nil || id <= 0 { + writeError(w, http.StatusBadRequest, + "INVALID_INPUT", + "Invalid input data", + "Product ID must be a positive integer") + return + } + + var p Product + if err := json.NewDecoder(r.Body).Decode(&p); err != nil { + writeError(w, http.StatusBadRequest, + "INVALID_INPUT", + "Invalid input data", + "Body must be valid JSON") + return + } + + // Basic validation + if p.SKU == "" || p.Manufacturer == "" || p.CategoryID <= 0 || p.ProductID <= 0 { + writeError(w, http.StatusBadRequest, + "INVALID_INPUT", + "Invalid input data", + "Missing or invalid product fields") + return + } + + // Ensure path ID matches body ID + if p.ProductID != id { + writeError(w, http.StatusBadRequest, + "INVALID_INPUT", + "Invalid input data", + "Product ID in path and body must match") + return + } + + // Check if product exists before updating + if _, exists := products[id]; !exists { + writeError(w, http.StatusNotFound, + "NOT_FOUND", + "Product not found", + "Cannot add details for a product that does not exist") + return + } + + // Update existing product + products[id] = p + // Return 204 No Content + w.WriteHeader(http.StatusNoContent) } -// postAlbums adds an album from JSON received in the request body. -func postAlbums(c *gin.Context) { - var newAlbum album +func getProduct(w http.ResponseWriter, r *http.Request) { + defer func() { + if rec := recover(); rec != nil { + writeError(w, http.StatusInternalServerError, + "INTERNAL_SERVER_ERROR", + "An unexpected error occurred", + fmt.Sprintf("%v", rec)) + } + }() // this is to add the 500 error response - // Call BindJSON to bind the received JSON to - // newAlbum. - if err := c.BindJSON(&newAlbum); err != nil { - return - } + vars := mux.Vars(r) + id, err := strconv.Atoi(vars["id"]) + if err != nil || id <= 0 { + writeError(w, http.StatusBadRequest, + "INVALID_INPUT", + "Invalid input data", + "Product ID must be a positive integer") + return + } - // Add the new album to the slice. - albums = append(albums, newAlbum) - c.IndentedJSON(http.StatusCreated, newAlbum) + p, exists := products[id] + if !exists { + writeError(w, http.StatusNotFound, + "NOT_FOUND", + "Product not found", + "No product found with the given ID") + return + } + + // Return 200 with JSON + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + json.NewEncoder(w).Encode(p) } -// getAlbumByID locates the album whose ID value matches the id -// parameter sent by the client, then returns that album as a response. -func getAlbumByID(c *gin.Context) { - id := c.Param("id") - - // Loop through the list of albums, looking for - // an album whose ID value matches the parameter. - for _, a := range albums { - if a.ID == id { - c.IndentedJSON(http.StatusOK, a) - return - } - } - c.IndentedJSON(http.StatusNotFound, gin.H{"message": "album not found"}) -} \ No newline at end of file +func main() { + // products[1] = Product{ + // ProductID: 1, + // SKU: "OLD123", + // Manufacturer: "Acme", + // CategoryID: 10, + // Weight: 100, + // SomeOtherID: 5, + // } + + for i := 1; i <= 50; i++ { + products[i] = Product{ + ProductID: i, + SKU: fmt.Sprintf("SKU-%04d", i), + Manufacturer: "Acme", + CategoryID: 10, + Weight: 100, + SomeOtherID: 5, + } + } + + router := mux.NewRouter() + router.HandleFunc("/products/{id}", getProduct).Methods("GET") + router.HandleFunc("/products/{id}/details", createOrUpdateProduct).Methods("POST") + fmt.Println("Server is running on port 8080") + if err := http.ListenAndServe(":8080", router); err != nil { + fmt.Println("Error starting server:", err) + os.Exit(1) + } +} diff --git a/terraform/.terraform.lock.hcl b/terraform/.terraform.lock.hcl index 1e006fd..5b84447 100644 --- a/terraform/.terraform.lock.hcl +++ b/terraform/.terraform.lock.hcl @@ -2,9 +2,11 @@ # Manual edits may be lost in future updates. provider "registry.terraform.io/hashicorp/aws" { - version = "6.7.0" + version = "6.7.0" + constraints = "~> 6.7.0" hashes = [ "h1:iP8jjtdbeNVowu1JgUx76SGU1JsYj5JX10eRdMg9XwA=", + "h1:vISrEI1xUh0w7NXTQ9m6ZEnQ1dv02yy+EJvxW78DAoI=", "zh:3c0a256f813e5e2c1e1aa137204ad9168ebe487f6cee874af9e9c78eb300568e", "zh:3c49dd75ea28395b29ba259988826b956c8adf6c0b59dd8874feb4f47bad976a", "zh:3e6e3e3bfc6594f4f9e2c017ee588c5fcad394b87dd0b68a3f37cd66001f3c8c", @@ -28,6 +30,7 @@ provider "registry.terraform.io/kreuzwerker/docker" { constraints = "~> 2.0" hashes = [ "h1:0GQGmz25xaSRbFyAGXHhU6nmhR4lYN5NYtc6S+wv7pw=", + "h1:7SILKY4Mjkbs/AHre2QQEaq5qUiOqOzmJwQABrUul4o=", "zh:02ca00d987b2e56195d2e97d82349f680d4b94a6a0d514dc6c0031317aec4f11", "zh:432d333412f01b7547b3b264ec85a2627869fdf5f75df9d237b0dc6a6848b292", "zh:4709e81fea2b9132020d6c786a1d1d02c77254fc0e299ea1bb636892b6cadac6", diff --git a/~$demo.docx b/~$demo.docx new file mode 100644 index 0000000..f1ceb47 Binary files /dev/null and b/~$demo.docx differ