Skip to content

Commit

Permalink
test: ✅ added index handler test
Browse files Browse the repository at this point in the history
  • Loading branch information
ngoldack committed Oct 19, 2023
1 parent d38f4d3 commit 73ff611
Show file tree
Hide file tree
Showing 8 changed files with 79 additions and 105 deletions.
35 changes: 31 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,39 @@
# vercel-chi
# vercel-go-chi

Demo application using vercel serverless functions to create a simple API with go using chi router.
This application also uses a PostgreSQL database served by vercel.

Technologies used:
## Technologies used

- [Go](https://go.dev/) - Programming language
- [Chi](https://go-chi.io/) - Router
- [Vercel](https://vercel.com/) - Serverless functions
- [PostgreSQL](https://www.postgresql.org/) - Database
- [Dagger](https://dagger.io/) - CI
- [Github Actions](https://github.com/features/actions) - CI Executor

## Using this template

To use this template, you can click on the "Use this template" button or clone it using git:

```bash
git clone https://github.com/ngoldack/vercel-go-chi.git
```

## Pre-requisites

To run this application locally, you need to have [Go](https://golang.org/) installed.

If you want to run the CI, you also need [Docker](https://www.docker.com/) and [Dagger](https://dagger.io) installed.

## Running locally

### CI (build, lint, test)

```bash
dagger run go run ci/main.go
```

### Dev server

```bash
go run ./cmd/server/main.go
```
2 changes: 1 addition & 1 deletion api/handler/index.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,6 @@ import (

func (ih *RootHandler) IndexHandler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
render.JSON(w, r, map[string]string{"message": fmt.Sprintf("Hello from %s", ih.db.DriverName())})
render.JSON(w, r, map[string]string{"message": fmt.Sprintf("Hello, %s!", r.RemoteAddr)})
}
}
28 changes: 28 additions & 0 deletions api/handler/index_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package handler_test

import (
"encoding/json"
"net/http/httptest"
"testing"

"github.com/ngoldack/vercel-chi/api/handler"
"github.com/stretchr/testify/require"
)

func TestIndexHandle(t *testing.T) {
req := httptest.NewRequest("GET", "/", nil)
w := httptest.NewRecorder()

rootHandler := handler.NewRootHandler()
rootHandler.IndexHandler().ServeHTTP(w, req)

result := w.Result()
require.Equal(t, 200, result.StatusCode, "should return 200 OK")
require.Equal(t, "application/json", result.Header.Get("Content-Type"), "should return JSON")

m := make(map[string]string)
err := json.NewDecoder(w.Result().Body).Decode(&m)
require.NoError(t, err, "should decode JSON")

require.True(t, len(m["message"]) > 0, "should return a message")
}
10 changes: 3 additions & 7 deletions api/handler/root.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
package handler

import "github.com/jmoiron/sqlx"
type RootHandler struct{}

type RootHandler struct {
db *sqlx.DB
}

func NewRootHandler(db *sqlx.DB) *RootHandler {
return &RootHandler{db: db}
func NewRootHandler() *RootHandler {
return &RootHandler{}
}
12 changes: 4 additions & 8 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,16 @@ require (
github.com/Khan/genqlient v0.6.0 // indirect
github.com/adrg/xdg v0.4.0 // indirect
github.com/ajg/form v1.5.1 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/vektah/gqlparser/v2 v2.5.6 // indirect
golang.org/x/crypto v0.9.0 // indirect
golang.org/x/sync v0.3.0 // indirect
golang.org/x/sys v0.12.0 // indirect
golang.org/x/text v0.13.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

require (
dagger.io/dagger v0.8.8
github.com/jackc/pgx/v5 v5.4.3
github.com/jmoiron/sqlx v1.3.5
github.com/joho/godotenv v1.5.1
github.com/lib/pq v1.10.9
github.com/stretchr/testify v1.8.4
)
33 changes: 9 additions & 24 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -20,51 +20,36 @@ github.com/go-chi/chi/v5 v5.0.10 h1:rLz5avzKpjqxrYwXNfmjkrYYXOyLJd37pz53UFHC6vk=
github.com/go-chi/chi/v5 v5.0.10/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
github.com/go-chi/render v1.0.3 h1:AsXqd2a1/INaIfUSKq3G5uA8weYx20FOsM7uSoCyyt4=
github.com/go-chi/render v1.0.3/go.mod h1:/gr3hVkmYR0YlEy3LxCuVRFzEu9Ruok+gFqbIofjao0=
github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE=
github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk=
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.4.3 h1:cxFyXhxlvAifxnkKKdlxv8XqUf59tDlYjnV5YYfsJJY=
github.com/jackc/pgx/v5 v5.4.3/go.mod h1:Ig06C2Vu0t5qXC60W8sqIthScaEnFvojjj9dSljmHRA=
github.com/jmoiron/sqlx v1.3.5 h1:vFFPA71p1o5gAeqtEAwLU4dnX2napprKtHr7PYIcN3g=
github.com/jmoiron/sqlx v1.3.5/go.mod h1:nRVWtLre0KfCLJvgxzCsLVMogSvQ1zNJtpYr2Ccp0mQ=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/mattn/go-sqlite3 v1.14.6 h1:dNPt6NO46WmLVt2DLNpwczCmdV5boIZ6g/tlDrlRUbg=
github.com/mattn/go-sqlite3 v1.14.6/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
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/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M=
github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA=
github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8=
github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.3 h1:RP3t2pwF7cMEbC1dqtB6poj3niw/9gnV4Cjg5oW5gtY=
github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/vektah/gqlparser/v2 v2.5.6 h1:Ou14T0N1s191eRMZ1gARVqohcbe1e8FrcONScsq8cRU=
github.com/vektah/gqlparser/v2 v2.5.6/go.mod h1:z8xXUff237NntSuH8mLFijZ+1tjV1swDbpDqjJmk6ME=
golang.org/x/crypto v0.9.0 h1:LF6fAI+IutBocDJ2OT0Q1g8plpYljMZ4+lty+dsqw3g=
golang.org/x/crypto v0.9.0/go.mod h1:yrmDGqONDYtNj3tH8X9dzUun2m2lzPa9ngI6/RUPGR0=
golang.org/x/sync v0.3.0 h1:ftCYgMx6zT/asHUrPw8BLLscYtGznsLAnjq5RH9P66E=
golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
golang.org/x/sys v0.0.0-20211025201205-69cdffdb9359/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0 h1:CM0HF96J0hcLAwsHPJZjfdNzs0gftsLfgKt57wWHJ0o=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k=
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
Expand Down
62 changes: 2 additions & 60 deletions internal/app/app.go
Original file line number Diff line number Diff line change
@@ -1,65 +1,7 @@
package app

import (
"context"
"log"
"os"
"time"

"github.com/jmoiron/sqlx"
"github.com/joho/godotenv"

"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/stdlib"

_ "github.com/lib/pq"
)

type App struct {
db *sqlx.DB
}
type App struct{}

func NewApp() *App {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}

db, err := getDB(os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}

return &App{
db: db,
}
}

func getDB(uri string) (*sqlx.DB, error) {
// before : directly using sqlx
// DB, err = sqlx.Connect("postgres", uri)
// after : using pgx to setup connection
DB, err := createPGX(uri)
if err != nil {
return nil, err
}
DB.SetMaxIdleConns(2)
DB.SetMaxOpenConns(4)
DB.SetConnMaxLifetime(time.Duration(30) * time.Minute)

return DB, nil
}

func createPGX(uri string) (*sqlx.DB, error) {
connConfig, _ := pgx.ParseConfig(uri)
afterConnect := stdlib.OptionAfterConnect(func(ctx context.Context, conn *pgx.Conn) error {
_, err := conn.Exec(ctx, `SELECT 1`)
if err != nil {
return err
}
return nil
})

pgxdb := stdlib.OpenDB(*connConfig, afterConnect)
return sqlx.NewDb(pgxdb, "pgx"), nil
return &App{}
}
2 changes: 1 addition & 1 deletion internal/app/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ func (app *App) NewRouter() chi.Router {
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)

rh := handler.NewRootHandler(app.db)
rh := handler.NewRootHandler()

r.Get("/", rh.IndexHandler())

Expand Down

0 comments on commit 73ff611

Please sign in to comment.