1. Yann Malet
  2. gowebexp

Commits

Yann Malet  committed af95e46

Simplified the project by using a global app variable. Removed the
handler package.

  • Participants
  • Parent commits 3999501
  • Branches master

Comments (0)

Files changed (3)

File handlers/common.go

  • Ignore whitespace
-package handlers
-
-import (
-	"fmt"
-	"github.com/gorilla/context"
-	"github.com/gorilla/mux"
-	"gowiki/storages"
-	"net/http"
-	"html/template"
-)
-
-
-// DISCUSS: Is creating a wrapper handler the best thing to do ?
-type Storage struct {
-	storage storages.Storage
-	router  *mux.Router
-	handler http.Handler
-}
-
-func NewStorageFromFunc(s storages.Storage, r *mux.Router, f http.HandlerFunc) Storage {
-	return Storage{storage: s, router: r, handler: f}
-}
-
-func (self Storage) ServeHTTP(w http.ResponseWriter, r *http.Request) {
-	defer context.Clear(r)
-	context.Set(r, "storage", self.storage)
-	context.Set(r, "router", self.router)
-	context.Set(r, "vars", mux.Vars(r))
-	self.handler.ServeHTTP(w, r)
-}
-
-func RequestInspector(w http.ResponseWriter, r *http.Request) {
-	fmt.Fprintf(w, "URL: %s, method: %s, vars: %s", r.URL, r.Method, context.Get(r, "vars"))
-}
-
-func IndexHandler(w http.ResponseWriter, r *http.Request) {
-	router := context.Get(r, "router").(*mux.Router)
-	pages_url, err := router.Get("page_list").URL()
-	if err != nil {
-		panic(err)
-	}
-	tmpl := template.Must(template.ParseFiles("templates/index.html", "templates/base.html"))
-	ctx := make(map[string]interface{})
-	ctx["pages_url"] = pages_url
-	ctx["title"] = "Web experiment with GO"
-	err = tmpl.ExecuteTemplate(w, "base", ctx)
-	if err != nil {
-		http.Error(w, err.Error(), http.StatusInternalServerError)
-		return
-	}
-}

File handlers/page.go

  • Ignore whitespace
-package handlers
-
-import (
-	"github.com/gorilla/context"
-	"gowiki/storages"
-	"html/template"
-	"net/http"
-)
-
-func Pages(w http.ResponseWriter, r *http.Request) {
-	localStorage := context.Get(r, "storage").(storages.Storage)
-	if r.Method == "POST" {
-		localStorage.AddPage(r.FormValue("name"), r.FormValue("slug"), r.FormValue("content"))
-		// Redirect to / after the creation of the page
-		http.Redirect(w, r, "/", 302)
-	}
-
-	// DISCUSS template inheritance it feels weird
-	t, err := template.ParseFiles("templates/pages.html", "templates/base.html")
-	if err != nil {
-		http.Error(w, err.Error(), http.StatusInternalServerError)
-		return
-	}
-	ctx := make(map[string]interface{})
-	ctx["storage"] = localStorage
-	err = t.ExecuteTemplate(w, "base", ctx)
-	if err != nil {
-		http.Error(w, err.Error(), http.StatusInternalServerError)
-	}
-}
-
-func PageDetail(w http.ResponseWriter, r *http.Request) {
-	// Retrieve the storage from the context and cast it as Storage
-	localStorage := context.Get(r, "storage").(storages.Storage)
-	localVars := context.Get(r, "vars").(map[string]string)
-
-	t, err := template.ParseFiles("templates/detail_page.html", "templates/base.html")
-	if err != nil {
-		http.Error(w, err.Error(), http.StatusInternalServerError)
-		return
-	}
-	ctx := make(map[string]interface{})
-	ctx["page"], err = localStorage.GetPageBySlug(localVars["slug"])
-	if err != nil {
-		http.NotFound(w, r)
-		return
-	}
-	err = t.ExecuteTemplate(w, "base", ctx)
-	if err != nil {
-		http.Error(w, err.Error(), http.StatusInternalServerError)
-		return
-	}
-}

File server.go

View file
  • Ignore whitespace
 
 import (
 	"fmt"
+	"github.com/gorilla/context"
 	"github.com/gorilla/mux"
-	"gowiki/handlers"
 	"gowiki/storages"
+	"html/template"
 	"net/http"
 )
 
 // TODO: Use flag to set parameter: IP, PORT, path
 
-func main() {
-	// Create an instance of a MemStorage
-	fmt.Println("Loading the storage backend")
+type App struct {
+	router  *mux.Router
+	storage storages.Storage
+}
+
+func NewApp() *App {
 	storage, err := storages.NewMemStorage()
 	if err != nil {
 		fmt.Println("An error occured while creating the storage")
 	}
+	return &App{router: mux.NewRouter(), storage: storage}
+}
 
-	// request multiplexer
-	router := mux.NewRouter()
-	router.Handle("/inspect/{slug}/",
-		handlers.NewStorageFromFunc(storage, router, handlers.RequestInspector)).Name("inspector")
+// Initialize my app object
+var app = NewApp()
+
+func RequestInspector(w http.ResponseWriter, r *http.Request) {
+	defer context.Clear(r)
+	fmt.Fprintf(w, "URL: %s, method: %s, vars: %s", r.URL, r.Method, mux.Vars(r))
+}
 
-	router.Handle("/pages/{slug}/",
-		handlers.NewStorageFromFunc(storage, router, handlers.PageDetail)).Name("page_detail")
+func IndexHandler(w http.ResponseWriter, r *http.Request) {
+	defer context.Clear(r)
+	pages_url, err := app.router.Get("page_list").URL()
+	if err != nil {
+		panic(err)
+	}
+	tmpl := template.Must(template.ParseFiles("templates/index.html", "templates/base.html"))
+	ctx := make(map[string]interface{})
+	ctx["pages_url"] = pages_url
+	ctx["title"] = "Web experiment with GO"
+	err = tmpl.ExecuteTemplate(w, "base", ctx)
+	if err != nil {
+		http.Error(w, err.Error(), http.StatusInternalServerError)
+		return
+	}
+}
 
-	router.Handle("/pages/",
-		handlers.NewStorageFromFunc(storage, router, handlers.Pages)).Name("page_list")
+func Pages(w http.ResponseWriter, r *http.Request) {
+	defer context.Clear(r)
+	localStorage := app.storage
+	if r.Method == "POST" {
+		localStorage.AddPage(r.FormValue("name"), r.FormValue("slug"), r.FormValue("content"))
+		// Redirect to / after the creation of the page
+		http.Redirect(w, r, "/", 302)
+	}
 
-	router.Handle("/",
-		handlers.NewStorageFromFunc(storage, router, handlers.IndexHandler)).Name("index")
+	// DISCUSS template inheritance it feels weird
+	t, err := template.ParseFiles("templates/pages.html", "templates/base.html")
+	if err != nil {
+		http.Error(w, err.Error(), http.StatusInternalServerError)
+		return
+	}
+	ctx := make(map[string]interface{})
+	ctx["storage"] = localStorage
+	err = t.ExecuteTemplate(w, "base", ctx)
+	if err != nil {
+		http.Error(w, err.Error(), http.StatusInternalServerError)
+	}
+}
+
+func PageDetail(w http.ResponseWriter, r *http.Request) {
+	defer context.Clear(r)
+	// Retrieve the storage from the context and cast it as Storage
+	localStorage := app.storage
+	localVars := mux.Vars(r)
+
+	t, err := template.ParseFiles("templates/detail_page.html", "templates/base.html")
+	if err != nil {
+		http.Error(w, err.Error(), http.StatusInternalServerError)
+		return
+	}
+	ctx := make(map[string]interface{})
+	ctx["page"], err = localStorage.GetPageBySlug(localVars["slug"])
+	if err != nil {
+		http.NotFound(w, r)
+		return
+	}
+	err = t.ExecuteTemplate(w, "base", ctx)
+	if err != nil {
+		http.Error(w, err.Error(), http.StatusInternalServerError)
+		return
+	}
+}
+
+func main() {
+	// Create an instance of a MemStorage
+	fmt.Println("Loading the storage backend")
+
+	// request multiplexer
+	app.router.HandleFunc("/inspect/{slug}/", RequestInspector).Name("inspector")
+	app.router.HandleFunc("/pages/{slug}/", PageDetail).Name("page_detail")
+	app.router.HandleFunc("/pages/", Pages).Name("page_list")
+	app.router.HandleFunc("/", IndexHandler).Name("index")
 
 	// Start serving
 	fmt.Println("Starting server on : http://127.0.0.1:8080")
-	http.Handle("/", router)
+	http.Handle("/", app.router)
 	// Serving static file
 	http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static/"))))