Skip to content

Commit 7bc1f3c

Browse files
author
Matthew Borders
committed
Changed Port/EnableDB to public on Server; added BasePath
1 parent 203a76e commit 7bc1f3c

2 files changed

Lines changed: 35 additions & 14 deletions

File tree

README.md

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,24 @@ Mux-based REST API server container with Postgres support
1111
Documentation here: https://godoc.org/github.com/borderstech/requiem
1212

1313
## Example Usage
14+
### Without DB
1415
```go
15-
s := requiem.Server{
16-
Port: 8080,
17-
Controllers: [ ... IHttpController ],
18-
EnableDB: true
19-
}
16+
s := requiem.NewServer(... controllers)
17+
s.Start()
18+
```
19+
20+
### With DB
21+
```go
22+
s := requiem.NewServerWithDB(... controllers)
23+
s.EnableDB = true
24+
s.Start()
25+
```
2026

27+
### Change port or base path
28+
```go
29+
s := requiem.NewServerWithDB(... controllers)
30+
s.Port = 9090
31+
s.BasePath = "/rest"
2132
s.Start()
2233
```
2334

server.go

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,43 +7,53 @@ import (
77
"github.com/jinzhu/gorm"
88
)
99

10+
const (
11+
defaultPort = 8080
12+
defaultBasePath = "/api"
13+
)
14+
1015
// Server represents a REST API server container
16+
// Default port is 8080
17+
// Default path is /api
1118
type Server struct {
12-
port int
19+
Port int
20+
BasePath string
1321
controllers []IHttpController
14-
enableDB bool
22+
EnableDB bool
1523
}
1624

1725
// Start initializes the API and starts running on the specified port
26+
// Blocks on current thread
1827
func (s *Server) Start() {
1928
// Create logger
2029
InitLogger()
2130

2231
var db *gorm.DB
23-
if s.enableDB {
32+
if s.EnableDB {
2433
db = newDBConnection()
2534
defer db.Close()
2635
}
2736

2837
// Create API router and load controllers
29-
r := newRouter("/api", db, s.controllers)
38+
r := newRouter(s.BasePath, db, s.controllers)
3039
r.printRoutes()
3140

3241
// Create HTTP server using API router
3342
srv := &http.Server{
3443
Handler: r.MuxRouter,
35-
Addr: fmt.Sprintf(":%d", s.port),
44+
Addr: fmt.Sprintf(":%d", s.Port),
3645
}
3746

38-
Logger.Info("Starting server on port %d", s.port)
47+
Logger.Info("Starting server on port %d", s.Port)
3948
Logger.Fatal(srv.ListenAndServe().Error())
4049
}
4150

4251
// NewServer creates a route-based REST API server instance
43-
func NewServer(port int, enableDB bool, controllers ...IHttpController) *Server {
52+
func NewServer(controllers ...IHttpController) *Server {
4453
return &Server{
45-
port: port,
46-
enableDB: enableDB,
54+
Port: defaultPort,
55+
BasePath: defaultBasePath,
56+
EnableDB: false,
4757
controllers: controllers,
4858
}
4959
}

0 commit comments

Comments
 (0)