-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
59 lines (47 loc) · 1.4 KB
/
server.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 (
"context"
"fmt"
"log"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/render"
_ "github.com/go-sql-driver/mysql"
"github.com/lucas-j-k/go-sqlc-api/api"
"github.com/lucas-j-k/go-sqlc-api/sqldb"
"github.com/spf13/viper"
)
func main() {
ctx := context.Background()
// initialize env vars and SQL connection
viper.SetConfigFile(".env")
viper.ReadInConfig()
port := viper.Get("PORT")
err := sqldb.Connect()
if err != nil {
log.Panic("Unable to connect to MYSQL")
}
// initialize SQLC and http controller
queries := sqldb.New(sqldb.DB)
questionsController := api.NewQuestionController(queries, sqldb.DB, ctx)
// setup router
r := chi.NewRouter()
r.Use(middleware.Logger)
r.Use(render.SetContentType(render.ContentTypeJSON))
// route handlers
r.Route("/questions", func(r chi.Router) {
r.Get("/{id}", questionsController.GetQuestionById)
r.Put("/{id}", questionsController.UpdateQuestion)
r.Delete("/{id}", questionsController.DeleteQuestion)
r.Post("/{id}/answers", questionsController.InsertAnswer)
r.Get("/", questionsController.ListQuestions)
r.Post("/", questionsController.InsertQuestion)
})
// healthcheck
r.Get("/ping", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Pong"))
})
fmt.Printf("Server running on port [%v]\n\n", port)
http.ListenAndServe(fmt.Sprintf(":%v", port), r)
}