-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
62 lines (52 loc) · 1.27 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
package main
import (
"fmt"
"log"
"net/http"
"github.com/gin-gonic/gin"
"github.com/korrawit/finalexam/customer"
"github.com/korrawit/finalexam/database"
"github.com/korrawit/finalexam/repository"
_ "github.com/lib/pq"
)
func main() {
// Initializing
db := database.PostgresDB{}
repo := repository.Repository{
DB: db,
}
customerContext := customer.CustomerContext{
Repo: repo,
}
createTableIfExist(repo)
r := setupRouter(customerContext)
r.Run(":2019")
}
func setupRouter(cc customer.CustomerContext) *gin.Engine {
r := gin.Default()
r.Use(authMiddleware)
r.POST("/customers", cc.CreateCustomerHandler)
r.GET("/customers/:id", cc.GetCustomerByIdHandler)
r.GET("/customers", cc.GetListOfCustomerHandler)
r.PUT("/customers/:id", cc.UpdateCustomerIdHandler)
r.DELETE("/customers/:id", cc.DeleteCustomerByIdHandler)
return r
}
func createTableIfExist(repo interface {
CreateTableIfNotExist() error
}) {
err := repo.CreateTableIfNotExist()
if err != nil {
s := fmt.Sprintf("Unable to create table: %v", err)
log.Fatal(s)
}
}
func authMiddleware(c *gin.Context) {
token := c.GetHeader("Authorization")
if token != "token2019" {
c.JSON(http.StatusUnauthorized, gin.H{"error": http.StatusText(http.StatusUnauthorized)})
c.Abort()
return
}
c.Next()
}