|
package main |
|
|
|
import ( |
|
"bytes" |
|
"encoding/json" |
|
"fmt" |
|
"html" |
|
"html/template" |
|
"io/ioutil" |
|
"log" |
|
"net/http" |
|
"os" |
|
) |
|
|
|
type Person struct { |
|
FirstName string `json:"firstname"` |
|
LastName string `json:"lastname"` |
|
} |
|
|
|
func getJSONFromURL(url string) []byte { |
|
resp, err := http.Get(url) |
|
if err != nil { |
|
log.Fatal(err) |
|
} |
|
|
|
json, err := ioutil.ReadAll(resp.Body) |
|
if err != nil { |
|
log.Fatal(err) |
|
} |
|
|
|
return json |
|
} |
|
|
|
func getUsers() []byte { |
|
return getJSONFromURL("https://jsonplaceholder.typicode.com/users") |
|
} |
|
|
|
func getPosts() []byte { |
|
return getJSONFromURL("https://jsonplaceholder.typicode.com/posts") |
|
} |
|
|
|
func main() { |
|
http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) { |
|
fmt.Fprintf(w, "Hello, world") |
|
}) |
|
|
|
http.HandleFunc("/hello/url", func(w http.ResponseWriter, r *http.Request) { |
|
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path)) |
|
}) |
|
|
|
http.HandleFunc("/hello/person", func(w http.ResponseWriter, r *http.Request) { |
|
// w.Header().Add("X-XSS-Protection", "1") |
|
fmt.Fprintf(w, "<html><body>") |
|
fmt.Fprintf(w, "Hello, %s", r.URL.Query().Get("name")) |
|
// fmt.Fprintf(w, "Hello, %s", html.EscapeString(r.URL.Query().Get("name"))) |
|
fmt.Fprintf(w, "</body></html>") |
|
}) |
|
|
|
http.HandleFunc("/hello/template", func(w http.ResponseWriter, r *http.Request) { |
|
|
|
t, err := template.New("T").Parse(` |
|
Hello, {{ .FirstName }} |
|
`) |
|
if err != nil { |
|
log.Fatal(err) |
|
} |
|
|
|
out := bytes.NewBufferString("") |
|
t.Execute(out, struct { |
|
FirstName string |
|
LastName string |
|
}{ |
|
FirstName: r.URL.Query().Get("firstname"), |
|
LastName: r.URL.Query().Get("lastname"), |
|
}) |
|
w.Write(out.Bytes()) |
|
}) |
|
|
|
http.HandleFunc("/hello/json", func(w http.ResponseWriter, r *http.Request) { |
|
|
|
h := Person{ |
|
FirstName: r.URL.Query().Get("firstname"), |
|
LastName: r.URL.Query().Get("lastname"), |
|
} |
|
|
|
in, err := json.Marshal(h) |
|
if err != nil { |
|
log.Fatal(err) |
|
} |
|
|
|
var out bytes.Buffer |
|
err = json.Indent(&out, in, "", " ") |
|
if err != nil { |
|
log.Fatal(err) |
|
} |
|
// _, err = w.Write(out.Bytes()) |
|
_, err = out.WriteTo(w) |
|
if err != nil { |
|
log.Fatal(err) |
|
} |
|
}) |
|
|
|
http.HandleFunc("/hello/goroutine", func(w http.ResponseWriter, r *http.Request) { |
|
|
|
usersChan := make(chan []byte) |
|
postsChan := make(chan []byte) |
|
|
|
go func(usersChan chan []byte) { |
|
usersChan <- getUsers() |
|
}(usersChan) |
|
|
|
go func(postsChan chan []byte) { |
|
postsChan <- getPosts() |
|
}(postsChan) |
|
|
|
users := <-usersChan |
|
posts := <-postsChan |
|
|
|
// users := getUsers() |
|
// posts := getPosts() |
|
|
|
w.Write(users) |
|
w.Write(posts) |
|
}) |
|
|
|
err := http.ListenAndServe(fmt.Sprintf(":%s", os.Getenv("PORT")), nil) |
|
log.Fatal(err) |
|
} |