|
package main |
|
|
|
import ( |
|
"encoding/json" |
|
"encoding/xml" |
|
"html/template" |
|
"net/http" |
|
"path" |
|
) |
|
|
|
type Profile struct { |
|
Name string |
|
Hobbies []string |
|
} |
|
|
|
func main() { |
|
http.HandleFunc("/", foo) |
|
http.HandleFunc("/text", bar) |
|
http.HandleFunc("/json", jjson) |
|
http.HandleFunc("/xml", xxml) |
|
http.HandleFunc("/img", ffile) |
|
http.HandleFunc("/html", hhtml) |
|
http.HandleFunc("/layout", layout) |
|
http.ListenAndServe(":3000", nil) |
|
} |
|
|
|
// Sending Headers Only |
|
func foo(w http.ResponseWriter, r *http.Request) { |
|
w.Header().Set("Server", "A Go Web Server") |
|
w.WriteHeader(200) |
|
} |
|
|
|
// Rendering Plain Text |
|
func bar(w http.ResponseWriter, r *http.Request) { |
|
w.Write([]byte("OK")) |
|
} |
|
|
|
// Rendering JSON |
|
func jjson(w http.ResponseWriter, r *http.Request) { |
|
profile := Profile{"Jack", []string{"Python", "Js", "Golang", "Java", "C/C++"}} |
|
js, err := json.Marshal(profile) |
|
if err != nil { |
|
http.Error(w, err.Error(), http.StatusInternalServerError) |
|
return |
|
} |
|
w.Header().Set("Content-Type", "application/json") |
|
w.Write(js) |
|
} |
|
|
|
// Rendering XML |
|
func xxml(w http.ResponseWriter, r *http.Request) { |
|
profile := Profile{"Rose", []string{"A", "BV", "CDE"}} |
|
x, err := xml.MarshalIndent(profile, "", " ") |
|
if err != nil { |
|
http.Error(w, err.Error(), http.StatusInternalServerError) |
|
return |
|
} |
|
w.Header().Set("Content-Type", "application/xml") |
|
w.Write(x) |
|
} |
|
|
|
// Sending file |
|
func ffile(w http.ResponseWriter, r *http.Request) { |
|
fp := path.Join("images", "had.jpg") |
|
http.ServeFile(w, r, fp) |
|
} |
|
|
|
// Rendering HTML |
|
func hhtml(w http.ResponseWriter, r *http.Request) { |
|
profile := Profile{"Alex", []string{"snowboarding", "programming"}} |
|
|
|
fp := path.Join("templates", "index.html") |
|
tmpl, err := template.ParseFiles(fp) |
|
if err != nil { |
|
http.Error(w, err.Error(), http.StatusInternalServerError) |
|
return |
|
} |
|
|
|
if err := tmpl.Execute(w, profile); err != nil { |
|
http.Error(w, err.Error(), http.StatusInternalServerError) |
|
} |
|
} |
|
|
|
// Using Layouts and Nested Templates |
|
func layout(w http.ResponseWriter, r *http.Request) { |
|
profile := Profile{"BeginMan", []string{"snowboarding", "programming"}} |
|
|
|
lp := path.Join("templates", "layout.html") |
|
fp := path.Join("templates", "render_string.html") |
|
|
|
tmpl, err := template.ParseFiles(lp, fp) |
|
if err != nil { |
|
http.Error(w, err.Error(), http.StatusInternalServerError) |
|
return |
|
} |
|
|
|
if err := tmpl.Execute(w, profile); err != nil { |
|
http.Error(w, err.Error(), http.StatusInternalServerError) |
|
} |
|
|
|
} |