-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
59 lines (46 loc) · 1.33 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
package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"time"
"github.com/kushalshit27/go-rest-api/internal/config"
"github.com/kushalshit27/go-rest-api/internal/database"
"github.com/kushalshit27/go-rest-api/internal/middleware"
"github.com/kushalshit27/go-rest-api/internal/utils"
"github.com/kushalshit27/go-rest-api/post"
"github.com/gorilla/mux"
)
func routes(db *database.DB) *mux.Router {
router := mux.NewRouter()
router.Use(middleware.Logger)
postService := post.PostAPI(db)
postService.Register(
router.PathPrefix("/api").Subrouter(),
)
router.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(utils.ResponseError("error 404"))
})
return router
}
func main() {
// Load config from the path provided by the user
envPath := flag.String("env", ".env", "Path to environment file")
flag.Parse()
config := config.Load(*envPath)
// Init database connection
database := database.NewDB(config)
defer database.Close()
// Init server
addr := fmt.Sprintf(":%s", "8080")
log.Printf("[API] API running on: http://127.0.0.1:%s", "8080")
server := http.Server{
Addr: addr,
Handler: middleware.CORS(routes(database)),
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
}
log.Fatalln(server.ListenAndServe())
}