Skip to content

Commit

Permalink
Refactor Elastic Client
Browse files Browse the repository at this point in the history
Signed-off-by: Daksh Chauhan <dak-x@outlook.com>
  • Loading branch information
dak-x committed Aug 2, 2021
1 parent 482c5fb commit 1de57d2
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 38 deletions.
51 changes: 51 additions & 0 deletions elastic/elastic.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package elastic

import (
"log"
"time"

"github.com/elastic/go-elasticsearch/v7"
)

var client *elasticsearch.Client

func init() {

esCfg := elasticsearch.Config{
Addresses: []string{
"http://elastic:9200/",
},
}

client, err := elasticsearch.NewClient(esCfg)

if err != nil {
log.Fatalf("Cannot create Client: %v", err)
}

esInfo, err := client.Info()

var numRetries int = 0

for err != nil {
// Wait for the instane to get up and running.
time.Sleep(3 * time.Second)
numRetries++
if numRetries == 5 {
break
}
esInfo, err = client.Info()
}

if err != nil {
log.Fatalf("Elastic is not running %s", err)
}

log.Printf("ELASTIC IS UP: %v\n", esInfo)
log.Printf("STARTING SOKEMOTOR SERVICE \n")

}

func GetEsClint() *elasticsearch.Client {
return client
}
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ go 1.16
require github.com/gin-gonic/gin v1.7.2

require github.com/elastic/go-elasticsearch/v7 v7.13.1

58 changes: 20 additions & 38 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,52 +2,20 @@ package main

import (
"log"
"time"
"net/http"
"sokemotor/elastic"

"github.com/elastic/go-elasticsearch/v7"
"github.com/gin-gonic/gin"
)

func getEsClint() *elasticsearch.Client {

esCfg := elasticsearch.Config{
Addresses: []string{
"http://elastic:9200/",
},
}

es, err := elasticsearch.NewClient(esCfg)

if err != nil {
log.Fatalf("Cannot create Client: %v", err)
}

res, err := es.Info()

var numRetry int = 0

for err != nil {
time.Sleep(3 * time.Second)
numRetry++
if numRetry == 5 {
break
}
res, err = es.Info()
}

if err != nil {
log.Fatalf("Elastic is not running %s", err)
}

log.Printf("ELASTIC IS UP: %v", res)
log.Printf("STARTING SOKEMOTOR SERVICE")

return es
type htmlDocument struct {
Url string `json:"url"`
Dom string `json:"dom"`
}

func main() {

_ = getEsClint()
_ = elastic.GetEsClint()

app := gin.Default()
app.GET("/search/:query", searchHandler)
Expand All @@ -65,4 +33,18 @@ func documentHandler(c *gin.Context) {

func processHtml(c *gin.Context) {

var v htmlDocument

err := c.Bind(&v)

if err != nil {
log.Printf("Error %v", err)
} else {
log.Printf("Recevied: %v", v.Url)
}

c.JSON(http.StatusCreated, gin.H{
"url": v.Url,
"Created": "true",
})
}

0 comments on commit 1de57d2

Please sign in to comment.