Browse Source

add context values into example template page

tags/v0.9.0
jimzhan 9 years ago
parent
commit
ac5381f603
3 changed files with 11 additions and 3 deletions
  1. +7
    -1
      example/main.go
  2. +1
    -1
      example/views/index.html
  3. +3
    -1
      livereload/middleware.go

+ 7
- 1
example/main.go View File

"github.com/goanywhere/rex/livereload" "github.com/goanywhere/rex/livereload"
) )


type User struct {
Username string
}

func Index(w http.ResponseWriter, r *http.Request) { func Index(w http.ResponseWriter, r *http.Request) {
if html, err := template.ParseFiles(filepath.Join("views", "index.html")); err != nil { if html, err := template.ParseFiles(filepath.Join("views", "index.html")); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError) http.Error(w, err.Error(), http.StatusInternalServerError)
} else { } else {
html.Execute(w, nil)
w.Header().Set("Content-Type", "text/html")
var user = User{Username: rex.Env.String("USER", "guest")}
html.Execute(w, user)
} }
} }



+ 1
- 1
example/views/index.html View File



<main> <main>
<div class="container"> <div class="container">
<h2>Index</h2>
<h2>Welcome, {{ .Username }}</h2>
</div> </div>
</main> </main>



+ 3
- 1
livereload/middleware.go View File

"regexp" "regexp"
"strings" "strings"


"github.com/Sirupsen/logrus"
"github.com/goanywhere/env" "github.com/goanywhere/env"
) )


func (self *writer) addJavaScript(data []byte) []byte { func (self *writer) addJavaScript(data []byte) []byte {
javascript := fmt.Sprintf(`<script src="//%s%s"></script> javascript := fmt.Sprintf(`<script src="//%s%s"></script>
</head>`, self.host, URL.JavaScript) </head>`, self.host, URL.JavaScript)
logrus.Infof("JS: %s", javascript)
return regexp.MustCompile(`</head>`).ReplaceAll(data, []byte(javascript)) return regexp.MustCompile(`</head>`).ReplaceAll(data, []byte(javascript))
} }




func Middleware(next http.Handler) http.Handler { func Middleware(next http.Handler) http.Handler {
// ONLY run this under debug mode. // ONLY run this under debug mode.
if !env.Bool("DEBUG", true) {
if !env.Bool("DEBUG") {
return next return next
} }
Start() Start()

Loading…
Cancel
Save