-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
259 lines (210 loc) · 5.68 KB
/
main.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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
package main
import (
"encoding/json"
"errors"
"flag"
"fmt"
"log"
"net/http"
"os"
"path"
"strconv"
"strings"
"text/tabwriter"
"github.com/ilyakaznacheev/cleanenv"
"github.com/jwalton/gchalk"
)
var ConfigPaths = []string{
".amock.json",
".amockrc.json",
".amock.json.json",
".amock.json.yml",
".amock.json.yaml",
".amock.json.toml",
"amock.config",
"amock.json",
"amock.yml",
"amock.yaml",
"amock.toml",
}
var DataDir = path.Join(".amock", "data")
var SchemaDir = path.Join(".amock", "schema")
var TablesDir = path.Join(".amock", "tables")
type Config struct {
Host string `yaml:"host" env:"AMOCK_HOST" env-default:"localhost"`
Port int `yaml:"port" env:"AMOCK_PORT" env-default:"8080"`
Dir string `yaml:"dir" env:"AMOCK_DIR"`
Entities []string `yaml:"entities" env:"AMOCK_ENTITIES"`
InitCount int `yaml:"initCount" env:"AMOCK_INIT_COUNT" env-default:"20"`
}
var config *Config
var db Database
func init() {
parseFlags()
Debug("Creating database from config...")
config, _ = parseConfigFiles(ConfigPaths...)
Debug("Configuration loaded", "config", config)
if config == nil {
log.Fatal("No configuration file found")
}
getHostFromArgs()
buildTablesFromConfig()
if _, err := os.Stat(DataDir); errors.Is(err, os.ErrNotExist) {
err = os.MkdirAll(DataDir, os.ModePerm)
if err != nil {
log.Fatal(err)
}
}
if _, err := os.Stat(SchemaDir); errors.Is(err, os.ErrNotExist) {
err = os.MkdirAll(SchemaDir, os.ModePerm)
if err != nil {
log.Fatal(err)
}
}
Debug("Database created")
db = *HydrateDatabase(&db)
}
func getHostFromArgs() {
host := flag.Arg(0)
if host != "" {
var noPrefix string
var prefix string
if strings.Contains(host, "http://") {
noPrefix = strings.TrimPrefix(host, "http://")
prefix = "http://"
} else if strings.Contains(host, "https://") {
noPrefix = strings.TrimPrefix(host, "https://")
prefix = "https://"
} else {
noPrefix = host
}
if strings.Contains(noPrefix, ":") {
parts := strings.Split(noPrefix, ":")
config.Host = prefix + parts[0]
port, err := strconv.Atoi(parts[1])
if err != nil {
log.Fatal(err)
}
config.Port = port
} else {
config.Host = host
}
}
}
func main() {
StartServer()
}
func StartServer() {
url := constructUrl()
fmt.Println(gchalk.Bold("Starting server at " + url))
fmt.Println("\nAvailable routes:")
writer := tabwriter.NewWriter(os.Stdout, 0, 8, 2, '\t', tabwriter.AlignRight)
router := InitHandlers(config, &db)
Debug("Initializing routes...")
Debug("Routes", "routes", Routes)
fmt.Println("-----------------------------------------------")
for _, route := range Routes {
_, err := fmt.Fprintln(writer, gchalk.Bold(RequestMethodColor(route.Method, false))+"\t"+url+route.Path+"\t"+gchalk.Dim("[entity: "+gchalk.WithItalic().Bold(strings.Split(route.Path, "/")[1])+"]"))
if err != nil {
Error("Error writing to tabwriter", "error", err)
}
err = writer.Flush()
if err != nil {
Error("Error flushing", "error", err)
}
}
fmt.Println("")
log.Fatal(http.ListenAndServe(config.Host+":"+strconv.Itoa(config.Port), LogRequest(router)))
}
func parseConfigFiles(files ...string) (*Config, error) {
var cfg Config
fileRead := false
for i := 0; i < len(files); i++ {
if _, err := os.Stat(files[i]); errors.Is(err, os.ErrNotExist) {
continue
}
err := cleanenv.ReadConfig(files[i], &cfg)
if err == nil {
fileRead = true
}
}
if !fileRead {
err := cleanenv.ReadEnv(&cfg)
if err != nil {
log.Printf("Error reading configuration from file or environment: %v\n", err)
return nil, err
}
}
return &cfg, nil
}
func buildTablesFromConfig() {
if _, err := os.Stat(TablesDir); errors.Is(err, os.ErrNotExist) {
err = os.MkdirAll(TablesDir, os.ModePerm)
if err != nil {
log.Fatal(err)
}
}
db.Tables = make(map[string]Table)
if config.Dir != "" {
dir, err := os.ReadDir(config.Dir)
if err != nil {
log.Fatal(err)
}
for _, entry := range dir {
filename := entry.Name()
table, name := getOrCreateTable(filename, path.Join(config.Dir, filename))
Debug("Table "+gchalk.Bold(name)+" created from file "+gchalk.Bold(filename), "table", name, "file", filename)
db.Tables[name] = *table
}
}
if len(config.Entities) > 0 {
for _, entity := range config.Entities {
table, name := getOrCreateTable(entity, entity)
db.Tables[name] = *table
}
}
}
func getOrCreateTable(filename string, definitionFile string) (*Table, string) {
createNew := false
tempTable := Table{}
var name string
if path.Ext(filename) == ".json" {
tableFilePath := path.Join(TablesDir, filename+".table")
name = strings.ToLower(filename[:len(filename)-5])
if _, err := os.Stat(tableFilePath); errors.Is(err, os.ErrNotExist) {
createNew = true
} else {
tableFile, err := os.ReadFile(tableFilePath)
if err != nil {
createNew = true
}
Debug("Table "+gchalk.Bold(name)+" found at "+gchalk.Italic(tableFilePath)+" - skipping...", "table", name, "file", tableFilePath)
err = json.Unmarshal(tableFile, &tempTable)
if err != nil {
createNew = true
}
}
}
if createNew {
tempTable = createNewTable(name, filename, definitionFile)
}
return &tempTable, name
}
func createNewTable(name string, filename string, definitionFile string) Table {
return Table{
Name: name,
DefinitionFile: definitionFile,
Definition: make(map[string]*Field),
File: filename,
LastAutoID: 1,
}
}
func constructUrl() string {
var url string
if strings.Contains(config.Host, "http://") || strings.Contains(config.Host, "https://") {
url = config.Host + ":" + strconv.Itoa(config.Port)
} else {
url = "http://" + config.Host + ":" + strconv.Itoa(config.Port)
}
return url
}