Skip to content
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

feat: add echo-mysql app for mysql demo #115

Merged
merged 9 commits into from
Aug 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions echo-mysql/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
MYSQL_USER=root
MYSQL_PASSWORD=password
MYSQL_HOST=localhost
MYSQL_PORT=3306
MYSQL_DBNAME=uss
3 changes: 3 additions & 0 deletions echo-mysql/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.idea/
bin/*

674 changes: 674 additions & 0 deletions echo-mysql/LICENSE

Large diffs are not rendered by default.

86 changes: 86 additions & 0 deletions echo-mysql/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
# echo-mysql
A simple golang based url shortner


# Requirments to run
1. Golang [How to install Golang](https://go.dev/doc/install)
2. Docker [How to install Docker?](https://docs.docker.com/engine/install/)


# Setting up the project
Run the following commands to clone the repository and download the necessary Go modules


``` bash
git clone https://github.com/keploy/samples-go.git && cd samples-go/echo-mysql
go mod download
```


# Running app

## Let's start the MySql Instance

``` bash
sudo docker run --name mysql-container -e MYSQL_ROOT_PASSWORD=password -e MYSQL_DATABASE=uss -p 3306:3306 --rm mysql:latest
```
## Build the application

``` bash
go build -o echo-mysql .
```

# Capture the Testcases

``` bash
sudo -E env PATH=$PATH oss record -c "./echo-mysql"
```

To generate testcases we just need to make some API calls. You can use Postman, Hoppscotch, or simply curl


1. Root Endpoint:
```bash
-> curl -X GET http://localhost:9090/
```


2. Health Check:
```bash
-> curl -X GET http://localhost:9090/healthcheck
```


3. Short URL:
```bash
-> curl -X POST http://localhost:9090/shorten -H "Content-Type: application/json" -d '{"url": "https://github.com"}'
```


4. Resolve short code:

```bash
-> curl -X GET http://localhost:9090/resolve/4KepjkTT
```

Now both these API calls were captured as a testcase and should be visible on the Keploy CLI. You should be seeing an app named keploy folder with the test cases we just captured and data mocks created.

![alt text](https://github.com/Hermione2408/samples-go/blob/app/echo-mysql/img/keploy_record.png?raw=true)

# Run the captured testcases

Now that we have our testcase captured, run the test file.

```bash
sudo -E env PATH=$PATH oss test -c "./echo-mysql" --delay 20
```

So no need to setup dependencies like MySQL, web-go locally or write mocks for your testing.

oss test runs the test cases captured in the previous step. It replays the captured API calls against the application to verify its behavior.

The application thinks it's talking to MySQL 😄

We will get output something like this:

![alt text](https://github.com/Hermione2408/samples-go/blob/app/echo-mysql/img/keploy_test.png?raw=true)
27 changes: 27 additions & 0 deletions echo-mysql/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
module github.com/hermione/echo-mysql

go 1.22.4

require (
github.com/itchyny/base58-go v0.2.2
github.com/joho/godotenv v1.5.1
github.com/labstack/echo v3.3.10+incompatible
gorm.io/driver/mysql v1.5.7
gorm.io/gorm v1.25.11
)

require (
github.com/dgrijalva/jwt-go v3.2.0+incompatible // indirect
github.com/go-sql-driver/mysql v1.7.0 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/labstack/gommon v0.4.2 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.2 // indirect
golang.org/x/crypto v0.24.0 // indirect
golang.org/x/net v0.21.0 // indirect
golang.org/x/sys v0.21.0 // indirect
golang.org/x/text v0.16.0 // indirect
)
48 changes: 48 additions & 0 deletions echo-mysql/go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
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/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/go-sql-driver/mysql v1.7.0 h1:ueSltNNllEqE3qcWBTD0iQd3IpL/6U+mJxLkazJ7YPc=
github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
github.com/itchyny/base58-go v0.2.2 h1:pswMT6rW2nRoELk5Mi8+xGLQPmDnlNnCwbfRCl2p7Mo=
github.com/itchyny/base58-go v0.2.2/go.mod h1:e7aEDHyQXm42jniwyoi+MaUeUdeWp58C5H20rTe52co=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/labstack/echo v3.3.10+incompatible h1:pGRcYk231ExFAyoAjAfD85kQzRJCRI8bbnE7CX5OEgg=
github.com/labstack/echo v3.3.10+incompatible/go.mod h1:0INS7j/VjnFxD4E2wkz67b8cVwCLbBmJyDaka6Cmk1s=
github.com/labstack/gommon v0.4.2 h1:F8qTUNXgG1+6WQmqoUWnz8WiEU60mXVVw0P4ht1WRA0=
github.com/labstack/gommon v0.4.2/go.mod h1:QlUFxVM+SNXhDL/Z7YhocGIBYOiwB0mXm1+1bAPHPyU=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
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/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/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
golang.org/x/crypto v0.24.0 h1:mnl8DM0o513X8fdIkmyFE/5hTYxbwYOjDS/+rK6qpRI=
golang.org/x/crypto v0.24.0/go.mod h1:Z1PMYSOR5nyMcyAVAIQSKCDwalqy85Aqn1x3Ws4L5DM=
golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.21.0 h1:rF+pYz3DAGSQAxAu1CbC7catZg4ebC4UIeIhKxBZvws=
golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4=
golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/mysql v1.5.7 h1:MndhOPYOfEp2rHKgkZIhJ16eVUIRf2HmzgoPmh7FCWo=
gorm.io/driver/mysql v1.5.7/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM=
gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
gorm.io/gorm v1.25.11 h1:/Wfyg1B/je1hnDx3sMkX+gAlxrlZpn6X0BXRlwXlvHg=
gorm.io/gorm v1.25.11/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ=
Binary file added echo-mysql/img/keploy_record.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added echo-mysql/img/keploy_test.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
77 changes: 77 additions & 0 deletions echo-mysql/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package main

import (
"fmt"
"log"
"net/http"

"github.com/joho/godotenv"
"github.com/hermione/echo-mysql/uss"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
)

func main() {
appConfig, err := godotenv.Read()
if err != nil {
log.Fatalf("Error reading .env file %s", err.Error())
}

uss.MetaStore = &uss.USSStore{}
err = uss.MetaStore.Connect(appConfig)
if err != nil {
log.Fatalf("Failed to connect to db %s", err.Error())
}

StartHTTPServer()
}

func StartHTTPServer() {
e := echo.New()
e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{
Format: `${remote_ip} [${time_rfc3339}] "${method} ${uri} HTTP/1.0" ${status} ${latency_human} ${bytes_out} ${error} "${user_agent}"` + "\n",
Skipper: func(c echo.Context) bool {
if c.Request().RequestURI == "/healthcheck" {
return true
}
return false
},
}))
e.Use(middleware.Recover())
e.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!")
})
e.GET("/healthcheck", func(c echo.Context) error {
return c.String(http.StatusOK, "good!")
})

e.GET("/resolve/:code", func(c echo.Context) error {
code := c.Param("code")
info := uss.MetaStore.FindByShortCode(code)
if info != nil {
return c.JSON(http.StatusOK, info)
} else {
return c.String(http.StatusNotFound, "Not Found.")
}
})

e.POST("/shorten", func(c echo.Context) error {
req := new(uss.ShortCodeInfo)
if err := c.Bind(req); err != nil {
return err
}

req.ShortCode = uss.GenerateShortLink(req.URL)
err := uss.MetaStore.Persist(req)
if err != nil {
return c.String(http.StatusInternalServerError, fmt.Sprintf("Failed Persisiting Entity with Error %s", err.Error()))
} else {
return c.JSON(http.StatusOK, req)
}
})

// automatically add routers for net/http/pprof e.g. /debug/pprof, /debug/pprof/heap, etc.
// go get github.com/hiko1129/echo-pprof
//echopprof.Wrap(e)
e.Logger.Fatal(e.Start(":9090"))
}
28 changes: 28 additions & 0 deletions echo-mysql/uss/short.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package uss

import (
"crypto/sha256"
"fmt"
"math/big"

"github.com/itchyny/base58-go"
)

func GenerateShortLink(initialLink string) string {
urlHashBytes := sha256Of(initialLink)
generatedNumber := new(big.Int).SetBytes(urlHashBytes).Uint64()
finalString := base58Encoded([]byte(fmt.Sprintf("%d", generatedNumber)))
return finalString[:8]
}

func sha256Of(input string) []byte {
algorithm := sha256.New()
algorithm.Write([]byte(input))
return algorithm.Sum(nil)
}

func base58Encoded(bytes []byte) string {
encoding := base58.BitcoinEncoding
encoded, _ := encoding.Encode(bytes)
return string(encoded)
}
79 changes: 79 additions & 0 deletions echo-mysql/uss/store.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package uss

import (
"fmt"
"log"
"time"

"gorm.io/driver/mysql"
"gorm.io/gorm"
)

type ShortCodeInfo struct {
UID uint64 `json:"id" sql:"AUTO_INCREMENT" gorm:"primary_key"`
ShortCode string `json:"shortcode" gorm:"uniqueIndex"`
URL string `json:"url"`
UpdatedAt time.Time `json:"updated_at"`
}

type USSStore struct {
db *gorm.DB
}

func (s *USSStore) Connect(config map[string]string) error {
// Open up our database connection.
var err error
mysqlDSN := fmt.Sprintf(
"%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local&tls=False",
config["MYSQL_USER"],
config["MYSQL_PASSWORD"],
config["MYSQL_HOST"],
config["MYSQL_PORT"],
config["MYSQL_DBNAME"],
)
s.db, err = gorm.Open(mysql.New(mysql.Config{
DSN: mysqlDSN,
DefaultStringSize: 256,
}), &gorm.Config{})
if err != nil {
return err
}

sqlDB, err := s.db.DB()
if err != nil {
return err
}

sqlDB.SetConnMaxLifetime(1 * time.Hour)
sqlDB.SetMaxIdleConns(100)
sqlDB.SetMaxOpenConns(512)

if err = s.db.AutoMigrate(&ShortCodeInfo{}); err != nil {
log.Fatal(fmt.Sprintf("Failed to create/update db tables with error %s", err.Error()))
}

return nil
}

func (s *USSStore) Close() {
db, _ := s.db.DB()
db.Close()
}

func (s *USSStore) Persist(info *ShortCodeInfo) error {
s.db.Save(info)
return nil
}

func (s *USSStore) FindByShortCode(shortCode string) *ShortCodeInfo {
var infos []ShortCodeInfo
s.db.Order("updated_at desc").Find(&infos, "short_code = ?", shortCode)
if len(infos) == 0 {
return nil
} else {
urlInfo := infos[0]
return &urlInfo
}
}

var MetaStore *USSStore
Loading