Skip to content

Commit

Permalink
Much better SRP handling - now have a server and database handled pur…
Browse files Browse the repository at this point in the history
…ely through model
  • Loading branch information
jamiefdhurst committed Mar 20, 2016
1 parent 437ddff commit 7d85638
Show file tree
Hide file tree
Showing 10 changed files with 113 additions and 112 deletions.
18 changes: 4 additions & 14 deletions lib/controller.go → controller/controller.go
Original file line number Diff line number Diff line change
@@ -1,28 +1,18 @@
package lib
package controller

import (
"database/sql"
"net/http"
)
import "net/http"

// Controller Super-struct for all controllers.
type Controller struct {
Db *sql.DB
Params []string
}

// ControllerInterface Interface to satisfy being a controller.
type ControllerInterface interface {
// Interface Interface to satisfy being a controller.
type Interface interface {
Run(w http.ResponseWriter, r *http.Request)
SetDb(db *sql.DB)
SetParams(p []string)
}

// SetDb Set the database pointer
func (c *Controller) SetDb(db *sql.DB) {
c.Db = db
}

// SetParams Set the current parameters on the controller.
func (c *Controller) SetParams(p []string) {
c.Params = p
Expand Down
3 changes: 1 addition & 2 deletions controller/error.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
package controller

import (
"journal/lib"
"net/http"
"text/template"
)

// Error Display a 404
type Error struct {
lib.Controller
Controller
}

// Run Error
Expand Down
4 changes: 1 addition & 3 deletions controller/index.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
package controller

import (
"journal/lib"
"journal/model"
"net/http"
"text/template"
)

// Index Handle displaying all blog entries
type Index struct {
lib.Controller
Controller
}

type indexData struct {
Expand All @@ -21,7 +20,6 @@ type indexData struct {
func (c *Index) Run(w http.ResponseWriter, r *http.Request) {

js := model.Journals{}
js.SetDb(c.Db)
js.FetchAll()
data := indexData{js.Journals, false}
query := r.URL.Query()
Expand Down
4 changes: 1 addition & 3 deletions controller/new.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
package controller

import (
"journal/lib"
"journal/model"
"net/http"
"text/template"
)

// New Handle creating a new entry
type New struct {
lib.Controller
Controller
}

// Run NewC
Expand All @@ -34,7 +33,6 @@ func (c *New) Run(w http.ResponseWriter, r *http.Request) {
}

js := model.Journals{}
js.SetDb(c.Db)
js.Create(0, model.Slugify(r.FormValue("title")), r.FormValue("title"), r.FormValue("date"), r.FormValue("content"))

http.Redirect(w, r, "/?saved=1", 302)
Expand Down
4 changes: 1 addition & 3 deletions controller/view.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
package controller

import (
"journal/lib"
"journal/model"
"net/http"
"text/template"
)

// View Handle displaying individual entry
type View struct {
lib.Controller
Controller
}

type viewData struct {
Expand All @@ -20,7 +19,6 @@ type viewData struct {
func (c *View) Run(w http.ResponseWriter, r *http.Request) {

js := model.Journals{}
js.SetDb(c.Db)
j := js.FindBySlug(c.Params[0])

if j.ID == 0 {
Expand Down
10 changes: 0 additions & 10 deletions lib/error.go

This file was deleted.

23 changes: 9 additions & 14 deletions lib/router.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package lib

import (
"database/sql"
"journal/controller"
"log"
"net/http"
"os"
Expand All @@ -13,18 +13,18 @@ type Route struct {
method string
uri string
matchable bool
controller ControllerInterface
controller controller.Interface
}

// Router Contian routes
type Router struct {
db *sql.DB
err ControllerInterface
err controller.Interface
routes []Route
server *Server
}

// Add A new route
func (m *Router) Add(t string, u string, a bool, c ControllerInterface) {
func (m *Router) Add(t string, u string, a bool, c controller.Interface) {
r := Route{t, u, a, c}
m.routes = append(m.routes, r)
}
Expand All @@ -46,7 +46,6 @@ func (m *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {

for _, route := range m.routes {
if r.URL.Path == route.uri && (r.Method == route.method || (r.Method == "" && route.method == "GET")) {
route.controller.SetDb(m.db)
route.controller.Run(w, r)
return
}
Expand All @@ -56,7 +55,6 @@ func (m *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
matched, _ := regexp.MatchString(route.uri, r.URL.Path)
if matched && (r.Method == route.method || (r.Method == "" && route.method == "GET")) {
re := regexp.MustCompile(route.uri)
route.controller.SetDb(m.db)
route.controller.SetParams(re.FindAllString(r.URL.Path, -1))
route.controller.Run(w, r)
return
Expand All @@ -67,12 +65,9 @@ func (m *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
m.err.Run(w, r)
}

// SetDb Set the db
func (m *Router) SetDb(db *sql.DB) {
m.db = db
}
// NewRouter Create a new router
func NewRouter(s *Server, e controller.Interface) Router {
var r []Route

// SetErr Set the err controller
func (m *Router) SetErr(err ControllerInterface) {
m.err = err
return Router{e, r, s}
}
57 changes: 57 additions & 0 deletions lib/server.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package lib

import (
"database/sql"
"journal/controller"
"journal/model"
"log"
"net/http"
)

// Server Contain the server
type Server struct {
db *sql.DB
router Router
}

// CheckErr Check and fatal if applicable
func (s Server) CheckErr(err error) {
if err != nil {
log.Fatal("Error reported: ", err)
}
}

func (s *Server) createDb() {
err := model.JournalCreateTable()
s.CheckErr(err)
log.Println("Database created")
}

func (s *Server) initRouter() {
s.router = NewRouter(s, &controller.Error{})
s.router.Add("GET", "/", false, &controller.Index{})
s.router.Add("GET", "/new", false, &controller.New{})
s.router.Add("POST", "/new", false, &controller.New{})
s.router.Add("GET", "\\/([\\w\\-]+)", true, &controller.View{})
}

// Run Run the server
func (s *Server) Run(mode string, port string) {
if mode == "create" {
s.createDb()
} else {
s.initRouter()
s.serve(port)
}
s.db.Close()
}

func (s *Server) serve(port string) {
log.Printf("Listening on port %s\n", port)
log.Fatal(http.ListenAndServe(":"+port, &s.router))
}

// NewServer Create an instance of the server
func NewServer() Server {
return Server{}
}
45 changes: 4 additions & 41 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,19 +1,13 @@
package main

import (
"database/sql"
"flag"
"fmt"
"journal/controller"
"journal/lib"
"log"
"net/http"
"os"

_ "github.com/mattn/go-sqlite3"
)

var db *sql.DB
var server lib.Server

func main() {
const version = "0.1"
Expand All @@ -27,40 +21,9 @@ func main() {

// Set CWD
os.Chdir(os.Getenv("GOPATH"))

// Load database
newdb, err := sql.Open("sqlite3", "./data/journal.db")
db = newdb
lib.CheckErr(err)
fmt.Printf("Journal v%s...\n-------------------\n\n", version)

if *mode == "create" {

_, err := db.Exec("CREATE TABLE `journal` (" +
"`id` INTEGER PRIMARY KEY AUTOINCREMENT, " +
"`slug` VARCHAR(255) NOT NULL, " +
"`title` VARCHAR(255) NOT NULL, " +
"`date` DATE NOT NULL, " +
"`content` TEXT NOT NULL" +
")")
lib.CheckErr(err)
db.Close()
log.Println("Database created")

} else {

m := &lib.Router{}
m.SetDb(db)
m.SetErr(&controller.Error{})
m.Add("GET", "/", false, &controller.Index{})
m.Add("GET", "/new", false, &controller.New{})
m.Add("POST", "/new", false, &controller.New{})
m.Add("GET", "\\/([\\w\\-]+)", true, &controller.View{})

log.Printf("Listening on port %s\n", *port)
log.Fatal(http.ListenAndServe(":"+*port, m))

db.Close()

}
// Create the server
server = lib.NewServer()
server.Run(*mode, *port)
}
Loading

0 comments on commit 7d85638

Please sign in to comment.