-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.go
826 lines (731 loc) · 21.5 KB
/
app.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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
/*
Copyright 2017 Atos
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"SLALite/generator"
"SLALite/model"
"SLALite/utils"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"time"
log "github.com/sirupsen/logrus"
"github.com/gorilla/mux"
"github.com/spf13/viper"
)
const (
defaultPort string = "8090"
defaultEnableSsl bool = false
defaultSslCertPath string = "cert.pem"
defaultSslKeyPath string = "key.pem"
portPropertyName = "port"
enableSslPropertyName = "enableSsl"
sslCertPathPropertyName = "sslCertPath"
sslKeyPathPropertyName = "sslKeyPath"
)
// App is a main application "object", to be built by main and testmain
// swagger:ignore
type App struct {
Router *mux.Router
Repository model.IRepository
Port string
SslEnabled bool
SslCertPath string
SslKeyPath string
externalIDs bool
validator model.Validator
}
// ApiError is the struct sent to client on errors
type ApiError struct {
Code string `json:"code"`
Message string `json:"message"`
}
func (e *ApiError) Error() string {
return e.Message
}
// endpoint represents an available operation represented by its HTTP method, the expected path for invocations and an optional help message.
// swagger:model
type endpoint struct {
// example: GET
Method string
// example: /providers
Path string
// example: Gets a list of registered providers
Help string
}
var api = map[string]endpoint{
"providers": endpoint{"GET", "/providers", "Providers"},
"agreements": endpoint{"GET", "/agreements", "Agreements"},
"templates": endpoint{"GET", "/templates", "Templates"},
}
func NewApp(config *viper.Viper, repository model.IRepository, validator model.Validator) (App, error) {
setDefaults(config)
logConfig(config)
a := App{
Port: config.GetString(portPropertyName),
SslEnabled: config.GetBool(enableSslPropertyName),
SslCertPath: config.GetString(sslCertPathPropertyName),
SslKeyPath: config.GetString(sslKeyPathPropertyName),
externalIDs: config.GetBool(utils.ExternalIDsPropertyName),
validator: validator,
}
// default templates
utils.LoadDefaultTemplates(repository)
// initialize App
a.initialize(repository)
/*
* TODO Return error if files not found, for ex.
*/
return a, nil
}
func setDefaults(config *viper.Viper) {
config.SetDefault(portPropertyName, defaultPort)
config.SetDefault(sslCertPathPropertyName, defaultSslCertPath)
config.SetDefault(sslKeyPathPropertyName, defaultSslKeyPath)
}
func logConfig(config *viper.Viper) {
ssl := "no"
if config.GetBool(enableSslPropertyName) == true {
ssl = fmt.Sprintf(
"(cert='%s', key='%s')",
config.GetString(sslCertPathPropertyName),
config.GetString(sslKeyPathPropertyName))
}
log.Printf("HTTP/S configuration\n"+
"\tport: %v\n"+
"\tssl: %v\n",
config.GetString(portPropertyName),
ssl)
}
// Initialize initializes the REST API passing the db connection
func (a *App) initialize(repository model.IRepository) {
a.Repository = repository
a.Router = mux.NewRouter().StrictSlash(true)
a.Router.HandleFunc("/", a.Index).Methods("GET")
a.Router.Methods("GET").Path("/providers").Handler(logger(a.GetAllProviders))
a.Router.Methods("GET").Path("/providers/{id}").Handler(logger(a.GetProvider))
a.Router.Methods("POST").Path("/providers").Handler(logger(a.CreateProvider))
a.Router.Methods("DELETE").Path("/providers/{id}").Handler(logger(a.DeleteProvider))
a.Router.Methods("GET").Path("/agreements").Handler(logger(a.GetAgreements))
a.Router.Methods("GET").Path("/agreements/{id}").Handler(logger(a.GetAgreement))
a.Router.Methods("POST").Path("/agreements").Handler(logger(a.CreateAgreement))
a.Router.Methods("PATCH").Path("/agreements/{id}").Handler(logger(a.UpdateAgreement))
// All these PUT below are deprecated, and superseded by PATCH above
a.Router.Methods("PUT").Path("/agreements/{id}/start").Handler(logger(a.StartAgreement))
a.Router.Methods("PUT").Path("/agreements/{id}/stop").Handler(logger(a.StopAgreement))
a.Router.Methods("PUT").Path("/agreements/{id}/terminate").Handler(logger(a.TerminateAgreement))
a.Router.Methods("PUT").Path("/agreements/{id}").Handler(logger(a.UpdateAgreement))
a.Router.Methods("DELETE").Path("/agreements/{id}").Handler(logger(a.DeleteAgreement))
a.Router.Methods("GET").Path("/agreements/{id}/details").Handler(logger(a.GetAgreementDetails))
a.Router.Methods("GET").Path("/templates").Handler(logger(a.GetTemplates))
a.Router.Methods("GET").Path("/templates/{id}").Handler(logger(a.GetTemplate))
a.Router.Methods("POST").Path("/templates").Handler(logger(a.CreateTemplate))
a.Router.Methods("POST").Path("/create-agreement").Handler(logger(a.CreateAgreementFromTemplate))
a.Router.Methods("POST").Path("/notifications").Handler(logger(a.ReceiveNotification))
// swagger api
sh := http.StripPrefix("/swaggerui/", http.FileServer(http.Dir("./swaggerui/")))
a.Router.PathPrefix("/swaggerui/").Handler(sh)
}
// Run starts the REST API
func (a *App) Run() {
addr := ":" + a.Port
if a.SslEnabled {
log.Fatal(http.ListenAndServeTLS(addr, a.SslCertPath, a.SslKeyPath, a.Router))
} else {
log.Fatal(http.ListenAndServe(addr, a.Router))
}
}
// Index is the API index
// swagger:operation GET / index
//
// Returns the available operations
//
// ---
// produces:
// - application/json
// responses:
// '200':
// description: API description
// schema:
// type: object
// additionalProperties:
// "$ref": "#/definitions/endpoint"
func (a *App) Index(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(api)
}
func logger(f func(w http.ResponseWriter, r *http.Request)) http.Handler {
return loggerDecorator(http.HandlerFunc(f))
}
func loggerDecorator(inner http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
inner.ServeHTTP(w, r)
log.Printf(
"%s\t%s\t\t%s",
r.Method,
r.RequestURI,
time.Since(start),
)
})
}
func (a *App) getAll(w http.ResponseWriter, r *http.Request, f func() (interface{}, error)) {
list, err := f()
if err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
} else {
respondSuccessJSON(w, list)
}
}
func (a *App) get(w http.ResponseWriter, r *http.Request, f func(string) (interface{}, error)) {
vars := mux.Vars(r)
id := vars["id"]
provider, err := f(id)
if err != nil {
manageError(err, w)
} else {
respondSuccessJSON(w, provider)
}
}
func (a *App) create(w http.ResponseWriter, r *http.Request, decode func() error, create func() (model.Identity, error)) {
errDec := decode()
if errDec != nil {
respondWithError(w, http.StatusBadRequest, errDec.Error())
return
}
/* check errors */
created, err := create()
if err != nil {
manageError(err, w)
} else {
respondWithJSON(w, http.StatusCreated, created)
}
}
// Update operation where the resource is updated with the body passed in request
func (a *App) updateEntity(w http.ResponseWriter, r *http.Request, decode func() error, update func(id string) (model.Identity, error)) {
vars := mux.Vars(r)
id := vars["id"]
errDec := decode()
if errDec != nil {
respondWithError(w, http.StatusBadRequest, errDec.Error())
return
}
/* check errors */
updated, err := update(id)
if err != nil {
manageError(err, w)
} else {
respondWithJSON(w, http.StatusOK, updated)
}
}
// Any other update operation not covered by updateEntity (e.g., delete)
func (a *App) update(w http.ResponseWriter, r *http.Request, upd func(string) error) {
vars := mux.Vars(r)
id := vars["id"]
err := upd(id)
if err != nil {
manageError(err, w)
} else {
respondNoContent(w)
}
}
// GetAllProviders return all providers in db
// swagger:operation GET /providers getAllProviders
//
// Returns all registered providers
//
// ---
// produces:
// - application/json
// responses:
// '200':
// description: The complete list of registered providers
// schema:
// type: object
// additionalProperties:
// "$ref": "#/definitions/Providers"
func (a *App) GetAllProviders(w http.ResponseWriter, r *http.Request) {
a.getAll(w, r, func() (interface{}, error) {
return a.Repository.GetAllProviders()
})
}
// GetProvider gets a provider by REST ID
// swagger:operation GET /providers/{id} getProvider
//
// Returns a provider given its ID
//
// ---
// produces:
// - application/json
// parameters:
// - name: id
// in: path
// description: The identifier of the provider
// required: true
// type: string
// responses:
// '200':
// description: The provider with the ID
// schema:
// "$ref": "#/definitions/Provider"
// '404' :
// description: Provider not found
func (a *App) GetProvider(w http.ResponseWriter, r *http.Request) {
a.get(w, r, func(id string) (interface{}, error) {
return a.Repository.GetProvider(id)
})
}
// CreateProvider creates a provider passed by REST params
// swagger:operation POST /providers createProvider
//
// Creates a provider with the information passed in the request body
//
// ---
// produces:
// - application/json
// consumes:
// - application/json
// parameters:
// - name: provider
// in: body
// description: The provider to create
// required: true
// schema:
// "$ref": "#/definitions/Provider"
// responses:
// '200':
// description: The new provider that has been created
// schema:
// "$ref": "#/definitions/Provider"
func (a *App) CreateProvider(w http.ResponseWriter, r *http.Request) {
var provider model.Provider
a.create(w, r,
func() error {
return json.NewDecoder(r.Body).Decode(&provider)
},
func() (model.Identity, error) {
return a.Repository.CreateProvider(&provider)
})
}
// DeleteProvider deletes /provider/id
// swagger:operation DELETE /providers/{id} deleteProvider
//
// Deletes a provider given its ID
//
// ---
// produces:
// - application/json
// parameters:
// - name: id
// in: path
// description: The identifier of the provider
// required: true
// type: string
// responses:
// '200':
// description: The provider has been successfully deleted
// '404' :
// description: Provider not found
func (a *App) DeleteProvider(w http.ResponseWriter, r *http.Request) {
a.update(w, r, func(id string) error {
return a.Repository.DeleteProvider(&model.Provider{Id: id})
})
}
// GetAgreements return all agreements in db
// swagger:operation GET /agreements getAllAgreements
//
// Returns all registered agreements
//
// ---
// produces:
// - application/json
// responses:
// '200':
// description: The complete list of registered agreements
// schema:
// type: object
// additionalProperties:
// "$ref": "#/definitions/Agreements"
func (a *App) GetAgreements(w http.ResponseWriter, r *http.Request) {
v := r.URL.Query()
active := v.Get("active")
a.getAll(w, r, func() (interface{}, error) {
if active != "" {
return a.Repository.GetAgreementsByState(model.STARTED)
}
return a.Repository.GetAllAgreements()
})
}
// GetAgreement gets an agreement by REST ID
// swagger:operation GET /agreements/{id} getAgreement
//
// Returns a agreement given its ID
//
// ---
// produces:
// - application/json
// parameters:
// - name: id
// in: path
// description: The identifier of the agreement
// required: true
// type: string
// responses:
// '200':
// description: The agreement with the ID
// schema:
// "$ref": "#/definitions/Agreement"
// '404' :
// description: Agreement not found
func (a *App) GetAgreement(w http.ResponseWriter, r *http.Request) {
a.get(w, r, func(id string) (interface{}, error) {
return a.Repository.GetAgreement(id)
})
}
// GetAgreementDetails gets an agreement by REST ID
// swagger:operation GET /agreements/{id}/details getAgreementDetails
//
// Returns the agreement details given its ID
//
// ---
// produces:
// - application/json
// parameters:
// - name: id
// in: path
// description: The identifier of the agreement
// required: true
// type: string
// responses:
// '200':
// description: The agreement details with the provided ID
// schema:
// "$ref": "#/definitions/Details"
// '404' :
// description: Agreement not found
func (a *App) GetAgreementDetails(w http.ResponseWriter, r *http.Request) {
a.get(w, r, func(id string) (interface{}, error) {
agreement, error := a.Repository.GetAgreement(id)
return agreement.Details, error
})
}
// CreateAgreement creates a agreement passed by REST params
// swagger:operation POST /agreements createAgreement
//
// Creates an agreement with the information passed in the request body
//
// ---
// produces:
// - application/json
// consumes:
// - application/json
// parameters:
// - name: agreement
// in: body
// description: The agreement to create
// required: true
// schema:
// "$ref": "#/definitions/Agreement"
// responses:
// '200':
// description: The new agreement that has been created
// schema:
// "$ref": "#/definitions/Agreement"
func (a *App) CreateAgreement(w http.ResponseWriter, r *http.Request) {
var agreement model.Agreement
a.create(w, r,
func() error {
return json.NewDecoder(r.Body).Decode(&agreement)
},
func() (model.Identity, error) {
return a.Repository.CreateAgreement(&agreement)
})
}
// DeleteAgreement deletes an agreement by id
// swagger:operation DELETE /agreements/{id} deleteAgreement
//
// Deletes an agreement given its ID
//
// ---
// produces:
// - application/json
// parameters:
// - name: id
// in: path
// description: The identifier of the agreement
// required: true
// type: string
// responses:
// '200':
// description: The agreement has been successfully deleted
// '404' :
// description: Agreement not found
func (a *App) DeleteAgreement(w http.ResponseWriter, r *http.Request) {
a.update(w, r, func(id string) error {
return a.Repository.DeleteAgreement(&model.Agreement{Id: id})
})
}
// UpdateAgreement updates the only fields updateable by REST in an agreement: state
// and assessment.monitoringURL.
// The Id in the body is ignored; only the id path is taken into account.
// swagger:operation PATCH /agreements/{id} updateAgreement
//
// Updates information in the agreement whose ID is passed as parameter.
// Only state and assessment.monitoringURL are updated.
//
// ---
// produces:
// - application/json
// parameters:
// - name: id
// in: path
// description: The identifier of the agreement
// required: true
// type: string
// - name: agreement
// in: body
// description: The information to update
// required: true
// schema:
// "$ref": "#/definitions/Agreement"
// responses:
// '200':
// description: The updated agreement
// schema:
// "$ref": "#/definitions/Agreement"
// '404' :
// description: Agreement not found
func (a *App) UpdateAgreement(w http.ResponseWriter, r *http.Request) {
var input model.Agreement
a.updateEntity(w, r,
func() error {
return json.NewDecoder(r.Body).Decode(&input)
},
func(id string) (model.Identity, error) {
newState := input.State
ag, err := a.Repository.UpdateAgreementState(id, newState)
if err != nil {
return ag, err
}
modified := false
if input.Assessment.MonitoringURL != "" {
ag.Assessment.MonitoringURL = input.Assessment.MonitoringURL
modified = true
}
if modified {
ag, err = a.Repository.UpdateAgreement(ag)
}
return ag, err
})
}
// StartAgreement starts monitoring an agreement
func (a *App) StartAgreement(w http.ResponseWriter, r *http.Request) {
a.update(w, r, func(id string) error {
_, err := a.Repository.UpdateAgreementState(id, model.STARTED)
return err
})
}
// StopAgreement stop monitoring an agreement
func (a *App) StopAgreement(w http.ResponseWriter, r *http.Request) {
a.update(w, r, func(id string) error {
_, err := a.Repository.UpdateAgreementState(id, model.STOPPED)
return err
})
}
// TerminateAgreement terminates an agreement
func (a *App) TerminateAgreement(w http.ResponseWriter, r *http.Request) {
a.update(w, r, func(id string) error {
_, err := a.Repository.UpdateAgreementState(id, model.TERMINATED)
return err
})
}
// GetTemplates return all templates in db
// swagger:operation GET /templates getAllTemplates
//
// Returns all registered templates
//
// ---
// produces:
// - application/json
// responses:
// '200':
// description: The complete list of registered templates
// schema:
// type: object
// additionalProperties:
// "$ref": "#/definitions/Templates"
func (a *App) GetTemplates(w http.ResponseWriter, r *http.Request) {
a.getAll(w, r, func() (interface{}, error) {
return a.Repository.GetAllTemplates()
})
}
// GetTemplate gets a template by REST ID
// swagger:operation GET /templates/{id} getTemplate
//
// Returns a template given its ID
//
// ---
// produces:
// - application/json
// parameters:
// - name: id
// in: path
// description: The identifier of the template
// required: true
// type: string
// responses:
// '200':
// description: The template with the ID
// schema:
// "$ref": "#/definitions/Template"
// '404' :
// description: Template not found
func (a *App) GetTemplate(w http.ResponseWriter, r *http.Request) {
a.get(w, r, func(id string) (interface{}, error) {
return a.Repository.GetTemplate(id)
})
}
// CreateTemplate creates a template passed by REST params
// swagger:operation POST /templates createTemplate
//
// Creates a template with the information passed in the request body
//
// ---
// produces:
// - application/json
// consumes:
// - application/json
// parameters:
// - name: template
// in: body
// description: The template to create
// required: true
// schema:
// "$ref": "#/definitions/Template"
// responses:
// '200':
// description: The new template that has been created
// schema:
// "$ref": "#/definitions/Template"
func (a *App) CreateTemplate(w http.ResponseWriter, r *http.Request) {
var template model.Template
a.create(w, r,
func() error {
return json.NewDecoder(r.Body).Decode(&template)
},
func() (model.Identity, error) {
return a.Repository.CreateTemplate(&template)
})
}
// CreateAgreementFromTemplate generates an agreement from a template and parameters
//
// swagger:operation POST /create-agreement createAgreementFromTemplate
//
// Creates an agreement from a template; templateId is the templateID to base the
// agreement from; agreementID is an output field, containing the ID of the created
// and stored agreement; parameters must contain a property for each placeholder to
// be substituted in the template.
//
// ---
// produces:
// - application/json
// consumes:
// - application/json
// parameters:
// - name: createAgreement
// in: body
// description: Parameters to create an agreement from a template
// required: true
// schema:
// "$ref": "#/definitions/CreateAgreement"
// responses:
// '200':
// description: The response contains the ID of the created agreement
// schema:
// "$ref": "#/definitions/CreateAgreement"
// '400' :
// description: Not all template placeholders were substituted
// '404' :
// description: Not found the TemplateID to create the agreement from
func (a *App) CreateAgreementFromTemplate(w http.ResponseWriter, r *http.Request) {
var in model.CreateAgreement
var t *model.Template
var ag *model.Agreement
a.create(w, r,
func() error {
return json.NewDecoder(r.Body).Decode(&in)
},
func() (model.Identity, error) {
var err error
t, err = a.Repository.GetTemplate(in.TemplateID)
if err != nil {
return nil, err
}
genmodel := generator.Model{
Template: *t,
Variables: in.Parameters,
}
ag, err = generator.Do(&genmodel, a.validator, a.externalIDs)
if err != nil {
return nil, err
}
ag, err = a.Repository.CreateAgreement(ag)
if err != nil {
return nil, err
}
out := in
out.AgreementID = ag.Id
return &out, nil
})
}
// ReceiveNotification is an endpoint to test the sending of notifications to
// external endpoints
func (a *App) ReceiveNotification(w http.ResponseWriter, r *http.Request) {
buf, err := ioutil.ReadAll(r.Body)
if err != nil {
manageError(err, w)
return
}
log.Infof("Received notification: %s", buf)
}
func manageError(err error, w http.ResponseWriter) {
switch err {
case model.ErrAlreadyExist:
respondWithError(w, http.StatusConflict, "Object already exist")
case model.ErrNotFound:
respondWithError(w, http.StatusNotFound, "Can't find object")
default:
if model.IsErrValidation(err) || generator.IsErrUnreplaced(err) {
respondWithError(w, http.StatusBadRequest, err.Error())
} else {
respondWithError(w, http.StatusInternalServerError, err.Error())
}
}
}
func respondWithError(w http.ResponseWriter, code int, message string) {
respondWithJSON(w, code, ApiError{strconv.Itoa(code), message})
}
func respondWithJSON(w http.ResponseWriter, code int, payload interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
enc := json.NewEncoder(w)
enc.SetEscapeHTML(false)
enc.Encode(payload)
}
func respondSuccessJSON(w http.ResponseWriter, payload interface{}) {
respondWithJSON(w, http.StatusOK, payload)
}
func respondNoContent(w http.ResponseWriter) {
w.WriteHeader(http.StatusNoContent)
}