forked from ardanlabs/gotraining
-
Notifications
You must be signed in to change notification settings - Fork 0
/
webserver2.go
84 lines (67 loc) · 1.77 KB
/
webserver2.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// All material is licensed under the Apache License Version 2.0, January 2004
// http://www.apache.org/licenses/LICENSE-2.0
// https://play.golang.org/p/N5c1LMZWe_
// Program to show how to run a basic web server with routing and templating.
package main
import (
"bytes"
"log"
"net/http"
"text/template"
"github.com/gorilla/mux"
)
// This is a basic struct to hold basic page data variables
type PageData struct {
Title string
Body string
}
func main() {
// We need to create a router
rt := mux.NewRouter().StrictSlash(true)
// Add the "index" or root path
rt.HandleFunc("/", Index)
// Fire up the server
log.Println("Starting server on http://localhost:8080")
log.Fatal(http.ListenAndServe(":8080", rt))
}
// Index is the "index" handler
func Index(w http.ResponseWriter, r *http.Request) {
// Fill out page data for index
pd := PageData{
Title: "Index Page",
Body: "This is the body of the page.",
}
// Render a template with our page data
tmpl, err := htmlTemplate(pd)
// If we got an error, write it out and exit
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
// All went well, so write out the template
w.Write([]byte(tmpl))
}
func htmlTemplate(pd PageData) (string, error) {
// Define a basic HTML template
html := `<HTML>
<head><title>{{.Title}}</title></head>
<body>
{{.Body}}
</body>
</HTML>`
// Parse the template
tmpl, err := template.New("index").Parse(html)
if err != nil {
return "", err
}
// We need somewhere to write the executed template to
var out bytes.Buffer
// Render the template with the data we passed in
if err := tmpl.Execute(&out, pd); err != nil {
// If we couldn't render, return a error
return "", err
}
// Return the template
return out.String(), nil
}