Skip to content

Instantly share code, notes, and snippets.

@yukpiz yukpiz/html_server.go
Last active Sep 8, 2018

Embed
What would you like to do?
package main
import (
"fmt"
"github.com/julienschmidt/httprouter"
"html/template"
"log"
"net/http"
)
type Profile struct {
Name string `json:"name"`
Age int `json:"age"`
Gender string `json:"gender"`
FavoriteFoods []string `json:"favorite_foods"`
}
var bob Profile = Profile{
Name: "Bob",
Age: 25,
Gender: "Man",
FavoriteFoods: []string{"Hamburger", "Cookie", "Chocolate"},
}
var alice Profile = Profile{
Name: "Alice",
Age: 24,
Gender: "Woman",
FavoriteFoods: []string{"Apple", "Orange", "Melon"},
}
func Index(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
t := template.Must(template.ParseFiles("templates/index.html.tpl"))
err := t.ExecuteTemplate(w, "index.html.tpl", nil)
if err != nil {
log.Fatal(err)
}
}
func GetProfile(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
name := p.ByName("name")
var resProfile Profile
if name == "Bob" {
resProfile = bob
} else if name == "Alice" {
resProfile = alice
} else {
http.Error(w, fmt.Sprintf("%d Not Found", http.StatusNotFound), http.StatusNotFound)
return
}
t := template.Must(template.ParseFiles("templates/profile.html.tpl"))
err := t.ExecuteTemplate(w, "profile.html.tpl", resProfile)
if err != nil {
log.Fatal(err)
}
}
func main() {
router := httprouter.New()
router.GET("/", Index)
router.GET("/profile/:name", GetProfile)
err := http.ListenAndServe(":8080", router)
if err != nil {
log.Fatal(err)
}
}
<html>
<body>
<h1>Hello golang!</h1>
<div><a href="/profile/Alice">Alice</a></div>
<div><a href="/profile/Bob">Bob</a></div>
</body>
</html>
<html>
<body>
<h1>Hello golang!</h1>
<div>Name: {{ .Name }}</div>
<div>Age: {{ .Age }}</div>
<div>Gender: {{ .Gender }}</div>
<div>Favorite Foods: {{ .FavoriteFoods }}</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.