54 lines
1.1 KiB
Go
54 lines
1.1 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"html/template"
|
|
"log"
|
|
"net/http"
|
|
)
|
|
|
|
type todo struct {
|
|
UserID int `json:"userId"`
|
|
ID int `json:"id"`
|
|
Title string `json:"title"`
|
|
Completed bool `json:"completed"`
|
|
}
|
|
|
|
var form = `
|
|
<h2>Todo #{{.ID}}</h2>
|
|
<div>{{printf "User %d" .UserID}}</div>
|
|
<div>{{printf "%s (status: %t)" .Title .Completed}}</div>
|
|
`
|
|
|
|
func handler(w http.ResponseWriter, r *http.Request) {
|
|
const base = "https://jsonplaceholder.typicode.com/"
|
|
resp, err := http.Get(base + r.URL.Path[1:])
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusServiceUnavailable)
|
|
return
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
var item todo
|
|
|
|
if err = json.NewDecoder(resp.Body).Decode(&item); err != nil {
|
|
http.Error(w, err.Error(), http.StatusServiceUnavailable)
|
|
return
|
|
}
|
|
tmpl, err := template.New("Mine").Parse(form)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
if err := tmpl.Execute(w, item); err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
}
|
|
|
|
func main() {
|
|
http.HandleFunc("/", handler)
|
|
log.Fatal(http.ListenAndServe(":9090", nil))
|
|
}
|