-
Notifications
You must be signed in to change notification settings - Fork 96
feat: add sample app for http postgres #209
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| keploy |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| FROM golang:1.24-alpine AS builder | ||
|
|
||
| WORKDIR /app | ||
| COPY go.mod go.sum ./ | ||
| RUN go mod download | ||
| COPY . . | ||
| RUN CGO_ENABLED=0 go build -o server . | ||
|
|
||
| FROM alpine:3.19 | ||
| WORKDIR /app | ||
| COPY --from=builder /app/server . | ||
| EXPOSE 8080 | ||
| CMD ["./server"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,103 @@ | ||
| # http-postgres | ||
|
|
||
| `http-postgres` is a small Go HTTP API backed by PostgreSQL. It is designed as a Keploy sample application for recording and replaying HTTP traffic together with Postgres interactions. | ||
|
|
||
| The app starts with `net/http`, connects to Postgres using `lib/pq`, runs startup migrations automatically, and exposes two resources: | ||
| - `companies` with a serial integer ID | ||
| - `projects` with a UUID ID | ||
|
|
||
| ## Endpoints | ||
|
|
||
| ### Companies | ||
| - `POST /companies` | ||
| - `GET /companies` | ||
| - `GET /companies/{name}` | ||
|
|
||
| ### Projects | ||
| - `POST /projects` | ||
| - `GET /projects` | ||
| - `GET /projects/{id}` | ||
| - `PUT /projects/{id}` | ||
|
|
||
| ## Prerequisites | ||
|
|
||
| - Go `1.24+` | ||
| - Docker and Docker Compose | ||
| - Keploy CLI | ||
|
|
||
| Install Keploy: | ||
|
|
||
| ```bash | ||
| curl --silent -O -L https://keploy.io/install.sh | ||
| source install.sh | ||
| ``` | ||
|
|
||
| ## Setup | ||
|
|
||
| ```bash | ||
| git clone https://github.com/keploy/samples-go.git | ||
| cd samples-go/http-postgres | ||
| go mod download | ||
| ``` | ||
|
|
||
| ## Run with Docker | ||
|
|
||
| Start the application and Postgres: | ||
|
|
||
| ```bash | ||
| docker compose up --build | ||
| ``` | ||
|
|
||
| The API will be available at `http://localhost:8080`. | ||
|
|
||
| ## Record Testcases with Keploy | ||
|
|
||
| Start recording: | ||
|
|
||
| ```bash | ||
| keploy record -c "docker compose up" --container-name api --delay 10 | ||
| ``` | ||
|
|
||
| In another terminal, generate traffic using the bundled scripts: | ||
|
|
||
| ```bash | ||
| ./test.sh | ||
| ./test_projects.sh | ||
| ``` | ||
|
|
||
| This records API testcases and Postgres mocks into the `keploy/` directory. | ||
|
|
||
| ## Replay Recorded Tests | ||
|
|
||
| Run the recorded testcases: | ||
|
|
||
| ```bash | ||
| keploy test -c "docker compose up" --container-name api --delay 20 | ||
| ``` | ||
|
|
||
| Keploy will replay the captured HTTP calls and mock the Postgres interactions during the test run. | ||
|
|
||
| ## Run Natively | ||
|
|
||
| If you want to run the app without Docker for the API process, start only Postgres through Compose: | ||
|
|
||
| ```bash | ||
| docker compose up -d db | ||
| ``` | ||
|
|
||
| Then run the server with local environment variables: | ||
|
|
||
| ```bash | ||
| DB_HOST=localhost \ | ||
| DB_PORT=5433 \ | ||
| DB_USER=postgres \ | ||
| DB_PASSWORD=postgres \ | ||
| DB_NAME=pg_replicate \ | ||
| go run . | ||
| ``` | ||
|
|
||
| ## Notes | ||
|
|
||
| - Database tables are created automatically on startup. | ||
| - `test.sh` focuses on company creation, duplicates, validation, and listing flows. | ||
| - `test_projects.sh` exercises UUID-based project create, get, update, and list flows. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| package db | ||
|
|
||
| import ( | ||
| "database/sql" | ||
| "fmt" | ||
| "os" | ||
|
|
||
| _ "github.com/lib/pq" | ||
| ) | ||
|
|
||
| func Connect() (*sql.DB, error) { | ||
| host := getEnv("DB_HOST", "localhost") | ||
| port := getEnv("DB_PORT", "5432") | ||
| user := getEnv("DB_USER", "postgres") | ||
| password := getEnv("DB_PASSWORD", "postgres") | ||
| dbname := getEnv("DB_NAME", "pg_replicate") | ||
|
|
||
| dsn := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable", | ||
| host, port, user, password, dbname) | ||
|
|
||
| db, err := sql.Open("postgres", dsn) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| if err := db.Ping(); err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| return db, nil | ||
| } | ||
|
|
||
| func Migrate(db *sql.DB) error { | ||
| query := ` | ||
| CREATE TABLE IF NOT EXISTS companies ( | ||
| id SERIAL PRIMARY KEY, | ||
| name TEXT NOT NULL UNIQUE, | ||
| created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() | ||
| ); | ||
| CREATE EXTENSION IF NOT EXISTS "pgcrypto"; | ||
| CREATE TABLE IF NOT EXISTS projects ( | ||
| id UUID PRIMARY KEY DEFAULT gen_random_uuid(), | ||
| name TEXT NOT NULL UNIQUE, | ||
| status TEXT NOT NULL DEFAULT 'active', | ||
| created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), | ||
| updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() | ||
| );` | ||
| _, err := db.Exec(query) | ||
| return err | ||
| } | ||
|
|
||
| func getEnv(key, fallback string) string { | ||
| if v := os.Getenv(key); v != "" { | ||
| return v | ||
| } | ||
| return fallback | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| services: | ||
| db: | ||
| image: postgres:16-alpine | ||
| environment: | ||
| POSTGRES_USER: postgres | ||
| POSTGRES_PASSWORD: postgres | ||
| POSTGRES_DB: pg_replicate | ||
| ports: | ||
| - "5433:5432" | ||
| volumes: | ||
| - pgdata:/var/lib/postgresql/data | ||
| healthcheck: | ||
| test: ["CMD-SHELL", "pg_isready -U postgres"] | ||
| interval: 2s | ||
| timeout: 5s | ||
| retries: 5 | ||
|
|
||
| api: | ||
| build: . | ||
| ports: | ||
| - "8080:8080" | ||
| environment: | ||
| DB_HOST: db | ||
| DB_PORT: "5432" | ||
| DB_USER: postgres | ||
| DB_PASSWORD: postgres | ||
| DB_NAME: pg_replicate | ||
| depends_on: | ||
| db: | ||
| condition: service_healthy | ||
|
|
||
| volumes: | ||
| pgdata: |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| module pg-replicate | ||
|
|
||
| go 1.24.4 | ||
|
|
||
| require ( | ||
| github.com/google/uuid v1.6.0 // indirect | ||
| github.com/lib/pq v1.11.2 // indirect | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= | ||
| github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= | ||
| github.com/lib/pq v1.11.2 h1:x6gxUeu39V0BHZiugWe8LXZYZ+Utk7hSJGThs8sdzfs= | ||
| github.com/lib/pq v1.11.2/go.mod h1:/p+8NSbOcwzAEI7wiMXFlgydTwcgTr3OSKMsD2BitpA= |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,110 @@ | ||
| package handler | ||
|
|
||
| import ( | ||
| "database/sql" | ||
| "encoding/json" | ||
| "net/http" | ||
| "strings" | ||
| ) | ||
|
|
||
| type Handler struct { | ||
| db *sql.DB | ||
| } | ||
|
|
||
| type Company struct { | ||
| ID int `json:"id"` | ||
| Name string `json:"name"` | ||
| CreatedAt string `json:"created_at"` | ||
| } | ||
AkashKumar7902 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| type CreateCompanyRequest struct { | ||
| Name string `json:"name"` | ||
| } | ||
|
|
||
| type ErrorResponse struct { | ||
| Error string `json:"error"` | ||
| } | ||
|
|
||
| func New(db *sql.DB) *Handler { | ||
| return &Handler{db: db} | ||
| } | ||
|
|
||
| func (h *Handler) CreateCompany(w http.ResponseWriter, r *http.Request) { | ||
| var req CreateCompanyRequest | ||
| if err := json.NewDecoder(r.Body).Decode(&req); err != nil { | ||
| writeJSON(w, http.StatusBadRequest, ErrorResponse{Error: "invalid request body"}) | ||
| return | ||
| } | ||
|
|
||
| req.Name = strings.TrimSpace(req.Name) | ||
| if req.Name == "" { | ||
| writeJSON(w, http.StatusBadRequest, ErrorResponse{Error: "name is required"}) | ||
| return | ||
| } | ||
|
|
||
| var company Company | ||
| err := h.db.QueryRow( | ||
| "INSERT INTO companies (name) VALUES ($1) RETURNING id, name, created_at", | ||
| req.Name, | ||
| ).Scan(&company.ID, &company.Name, &company.CreatedAt) | ||
AkashKumar7902 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| if err != nil { | ||
| if strings.Contains(err.Error(), "duplicate key") || strings.Contains(err.Error(), "unique constraint") { | ||
| writeJSON(w, http.StatusConflict, ErrorResponse{Error: "company already exists"}) | ||
| return | ||
| } | ||
| writeJSON(w, http.StatusInternalServerError, ErrorResponse{Error: "failed to create company"}) | ||
| return | ||
| } | ||
|
|
||
| writeJSON(w, http.StatusCreated, company) | ||
| } | ||
|
|
||
| func (h *Handler) ListCompanies(w http.ResponseWriter, r *http.Request) { | ||
| rows, err := h.db.Query("SELECT id, name, created_at FROM companies ORDER BY id") | ||
| if err != nil { | ||
| writeJSON(w, http.StatusInternalServerError, ErrorResponse{Error: "failed to list companies"}) | ||
| return | ||
| } | ||
| defer rows.Close() | ||
|
|
||
| companies := []Company{} | ||
| for rows.Next() { | ||
| var c Company | ||
| if err := rows.Scan(&c.ID, &c.Name, &c.CreatedAt); err != nil { | ||
| writeJSON(w, http.StatusInternalServerError, ErrorResponse{Error: "failed to scan company"}) | ||
| return | ||
| } | ||
| companies = append(companies, c) | ||
| } | ||
|
|
||
| writeJSON(w, http.StatusOK, companies) | ||
| } | ||
|
|
||
| func (h *Handler) GetCompany(w http.ResponseWriter, r *http.Request) { | ||
| name := strings.TrimPrefix(r.URL.Path, "/companies/") | ||
| if name == "" { | ||
| writeJSON(w, http.StatusBadRequest, ErrorResponse{Error: "company name is required"}) | ||
| return | ||
| } | ||
|
|
||
| var c Company | ||
| err := h.db.QueryRow("SELECT id, name, created_at FROM companies WHERE name = $1", name). | ||
| Scan(&c.ID, &c.Name, &c.CreatedAt) | ||
| if err == sql.ErrNoRows { | ||
| writeJSON(w, http.StatusNotFound, ErrorResponse{Error: "company not found"}) | ||
| return | ||
| } | ||
| if err != nil { | ||
| writeJSON(w, http.StatusInternalServerError, ErrorResponse{Error: "failed to get company"}) | ||
| return | ||
| } | ||
|
|
||
| writeJSON(w, http.StatusOK, c) | ||
| } | ||
|
|
||
| func writeJSON(w http.ResponseWriter, status int, data any) { | ||
| w.Header().Set("Content-Type", "application/json") | ||
| w.WriteHeader(status) | ||
| json.NewEncoder(w).Encode(data) | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.