-
Notifications
You must be signed in to change notification settings - Fork 108
/
Copy pathsalary_api.go
183 lines (155 loc) · 4.47 KB
/
salary_api.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
package main
import (
"salary/config"
"salary/elastic"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"encoding/json"
"io/ioutil"
"net/http"
"os"
"strconv"
"strings"
"time"
)
const (
fileName = "delay.txt"
)
var (
configFile = os.Getenv("CONFIG_FILE")
delayTime = os.Getenv("DELAY_TIME")
)
// EmployeeInfo struct will be the data structure for employee's information
type EmployeeInfo struct {
ID string `json:"id"`
Name string `json:"name"`
JobRole string `json:"job_role"`
JoiningDate string `json:"joining_date"`
Addresss string `json:"address"`
City string `json:"city"`
EmailID string `json:"email_id"`
AnnualPackage float64 `json:"annual_package"`
PhoneNumber string `json:"phone_number"`
}
// SalaryInfo struct will be the data structure for employee's information
type SalaryInfo struct {
ID string `json:"id"`
Name string `json:"name"`
Month string `json:"month"`
Salary float64 `json:"salary"`
}
func main() {
var waitTime int
conf, err := config.ParseFile(configFile)
logrus.SetFormatter(&logrus.JSONFormatter{})
if err != nil {
logrus.Errorf("Unable to parse configuration file for salary: %v", err)
}
logrus.Infof("Running employee-salary in webserver mode")
logrus.Infof("employee-salary is listening on port: %v", conf.Salary.APIPort)
logrus.Infof("Endpoint is available now - http://0.0.0.0:%v/create", conf.Salary.APIPort)
if delayTime == "" {
waitTime = 1
} else {
waitTime, _ = strconv.Atoi(delayTime)
}
time.Sleep(time.Duration(waitTime) * time.Second)
router := gin.Default()
config := cors.DefaultConfig()
config.AllowOrigins = []string{"*"}
router.Use(cors.New(config))
router.POST("/salary/configure/liveness", configureLiveness)
router.GET("/salary/search", fetchEmployeeSalary)
router.GET("/salary/healthz", healthCheck)
router.Run(":" + conf.Salary.APIPort)
}
func fetchEmployeeSalary(c *gin.Context) {
searchQuery := c.Request.URL.Query()
var searchValue string
response := &EmployeeInfo{}
for _, value := range searchQuery {
searchValue = strings.Join(value, "")
}
conf, err := config.ParseFile(configFile)
if err != nil {
logrus.Errorf("Unable to parse configuration file for management: %v", err)
}
data := elastic.SearchDataInElastic(conf, searchValue)
for _, parsedData := range data["hits"].(map[string]interface{})["hits"].([]interface{}) {
empData, err := json.Marshal(parsedData.(map[string]interface{})["_source"])
if err != nil {
logrus.Errorf("Unable to marshal response JSON: %v", err)
}
json.Unmarshal(empData, &response)
}
salaryData := SalaryInfo{
ID: response.ID,
Name: response.Name,
Salary: (response.AnnualPackage / 12),
Month: time.Now().UTC().Format("Jan"),
}
c.JSON(http.StatusOK, salaryData)
}
func healthCheck(c *gin.Context) {
var waitTime int
conf, err := config.ParseFile(configFile)
if err != nil {
logrus.Errorf("Unable to parse configuration file for management: %v", err)
}
status, err := elastic.CheckElasticHealth(conf)
if err != nil {
logrus.Errorf("Error while getting elasticsearch health: %v", err)
errorResponse(c, http.StatusBadRequest, "Elasticsearch is not running")
return
}
if Exists(fileName) {
content, err := ioutil.ReadFile(fileName)
if err != nil {
logrus.Errorf("Delay file doesn't exists: %v", err)
}
waitTime, _ = strconv.Atoi(string(content))
} else {
waitTime = 1
}
logrus.Infof("Response is slow by: %v seconds", waitTime)
time.Sleep(time.Duration(waitTime) * time.Second)
if status != false {
c.JSON(http.StatusOK, gin.H{
"status": "up",
"database": "elasticsearch",
"message": "Elasticsearch is running",
})
return
}
errorResponse(c, http.StatusBadRequest, "Elasticsearch is not running")
}
func configureLiveness(c *gin.Context) {
searchQuery := c.Request.URL.Query()
var searchValue string
for _, value := range searchQuery {
searchValue = strings.Join(value, "")
}
file, err := os.Create(fileName)
if err != nil {
logrus.Errorf("Unable to set delay period: %v", err)
errorResponse(c, http.StatusBadRequest, "Unable to set delay period")
return
}
defer file.Close()
file.WriteString(searchValue)
}
// Exists function checks if file exists or not
func Exists(name string) bool {
if _, err := os.Stat(name); err != nil {
if os.IsNotExist(err) {
return false
}
}
return true
}
func errorResponse(c *gin.Context, code int, err string) {
c.JSON(code, gin.H{
"error": err,
})
}