index.html
:
<h1>{{.Title}}</h1>
<h2>{{.Greeting}}</h2>
main.go
:
var templatePath = "templates/"
var templates = template.Must(template.ParseGlob(templatePath + "*.html"))
var validPath = regexp.MustCompile("^/(fibonacci|home)/([a-zA-Z0-9]+)$")
type Index struct {
Title string
Greeting string
}
func rootHandler(w http.ResponseWriter, r *http.Request) {
greeting, _ := greetings.Greeting(r.URL.Query().Get("name"))
result := Index{
Title: "GoLang RESTful API",
Greeting: greeting,
}
e := templates.ExecuteTemplate(w, "index.html", result)
if e != nil {
//log.Fatal(e)
http.Error(w, e.Error(), http.StatusInternalServerError)
}
}
greetings.go
:
func init() {
rand.Seed(time.Now().UnixNano())
}
// In Go, a function whose name starts with a capital letter can be called by a function not in the same package.
// This is known in Go as an exported name. For more about exported names, see Exported names in the Go tour.
func Greeting(name string) (string, error) {
message := ""
tz, _ := time.LoadLocation("Asia/Singapore")
if name != "" {
message = fmt.Sprintf("Hello %v! It is %s now.<br>%s</br>", name, time.Now().In(tz).Format("02-Jan-2006 15:04:05"), quote.Go())
} else {
message = fmt.Sprintf("Hello! It is %s now.<br>%s", time.Now().In(tz).Format("02-Jan-2006 15:04:05"), quote.Go())
}
return message, nil
}
func Greetings(names []string) (map[string]string, error) {
if names == nil {
return nil, errors.New("Invalid empty names!")
}
messages := make(map[string]string)
for _, name := range names {
message, err := Greeting(name)
if err != nil {
return nil, err
}
messages[name] = message
}
return messages, nil
}
func randomFormat() string {
formats := []string{
"Hi, %v. Welcome!",
"Great to see you, %v!",
"Hail, %v! Well met!",
}
return formats[rand.Intn(len(formats))]
}
浏览器中显示的输出是:
Hello Mickey! It is 17-Jan-2025 12:29:21 now.<br>Don't communicate by sharing memory, share memory by communicating.</br>
如何指示模板将
<br>
处理为换行符?
这是一个简单的修复。
type Index struct {
Title string
Greeting template.HTML
}
func rootHandler(w http.ResponseWriter, r *http.Request) {
greeting, _ := greetings.Greeting(r.URL.Query().Get("name"))
result := Index{
Title: "GoLang RESTful API",
Greeting: template.HTML(greeting),
}
e := templates.ExecuteTemplate(w, "index.html", result)
if e != nil {
//log.Fatal(e)
http.Error(w, e.Error(), http.StatusInternalServerError)
}
}