Skip to content

Instantly share code, notes, and snippets.

@muayyad-alsadi
Created August 21, 2015 22:37
Show Gist options
  • Save muayyad-alsadi/29a2c94c4f13f4cbdaa6 to your computer and use it in GitHub Desktop.
Save muayyad-alsadi/29a2c94c4f13f4cbdaa6 to your computer and use it in GitHub Desktop.
golang-web-demo
<html>
<head>
<title>{{.Title}}</title>
</head>
<body>
<h1>{{.Title}}</h1>
</body>
</html>
package main
import "fmt"
import "net/http"
import "html/template"
var myTemplate, _ = template.ParseFiles("index.html")
// var errTemplate = template.MustParseFile("error.html", nil)
type Page struct {
Title string
Body []byte
}
// takes handler function as parameter
func errorHandler(fn http.HandlerFunc) http.HandlerFunc {
// define anonymous func and return it
return func(w http.ResponseWriter, r *http.Request) {
// define anonymous function and defer its call
defer func(){
if r, ok := recover().(error); r != nil && !ok {
w.WriteHeader(500)
fmt.Fprintf(w, "Error: %v", r)
}
}()
fn(w, r)
}
}
func handler(w http.ResponseWriter, r *http.Request) {
myTemplate.Execute(w, &Page{Title: r.URL.Path[1:]})
//fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}
func main() {
http.HandleFunc("/", errorHandler(handler))
// http.HandleFunc("/foo", handler2)
fmt.Println("Listening: ...")
http.ListenAndServe(":8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment