From 1de57d2dc1a83b942ef2cbd63123a8e2c3fdc7a8 Mon Sep 17 00:00:00 2001 From: Daksh Chauhan Date: Mon, 2 Aug 2021 21:15:05 +0530 Subject: [PATCH] Refactor Elastic Client Signed-off-by: Daksh Chauhan --- elastic/elastic.go | 51 ++++++++++++++++++++++++++++++++++++++++ go.mod | 1 + main.go | 58 ++++++++++++++++------------------------------ 3 files changed, 72 insertions(+), 38 deletions(-) create mode 100644 elastic/elastic.go diff --git a/elastic/elastic.go b/elastic/elastic.go new file mode 100644 index 0000000..9fd5807 --- /dev/null +++ b/elastic/elastic.go @@ -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 +} diff --git a/go.mod b/go.mod index 145b494..cc696c2 100644 --- a/go.mod +++ b/go.mod @@ -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 + diff --git a/main.go b/main.go index 99002dc..013d6d3 100644 --- a/main.go +++ b/main.go @@ -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) @@ -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", + }) }