forked from LucasHild/go-ecommerce-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
65 lines (53 loc) · 1.4 KB
/
api.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
package api
import (
"log"
"net/http"
"github.com/go-chi/chi"
"github.com/gorilla/sessions"
"github.com/unrolled/render"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
// Server keeps track of router, config and more
type Server struct {
router chi.Router
config Config
cookieStore *sessions.CookieStore
googleOauthConf *oauth2.Config
}
var rnd *render.Render
// Start the server on port 8080
func (s *Server) Start() {
s.init()
log.Println("API now listening at http://localhost:8080...")
err := http.ListenAndServe(":8080", s.router)
if err != nil {
log.Fatal("Unable to start server:", err)
}
}
// Start the API server
func (s *Server) init() {
s.config = getConfig()
s.router = chi.NewRouter()
s.routes()
connectToDB(s.config)
rnd = render.New(render.Options{})
s.cookieStore = sessions.NewCookieStore(s.config.sessionKey)
s.googleOauthConf = &oauth2.Config{
ClientID: s.config.googleOauthClientID,
ClientSecret: s.config.googleOauthClientSecret,
RedirectURL: "http://127.0.0.1:8080/auth/google/redirect",
Scopes: []string{
"https://www.googleapis.com/auth/userinfo.email",
},
Endpoint: google.Endpoint,
}
}
// HomeHandler gives basic details about API
func (s *Server) HomeHandler(w http.ResponseWriter, r *http.Request) error {
rnd.JSON(w, http.StatusOK, map[string]string{
"project": "go-ecommerce-api",
"version": "v0",
})
return nil
}