networking and shit

This commit is contained in:
2026-09-18 11:42:15 -04:00
parent 1bae4e44b0
commit d7c01f2f0e
7 changed files with 128 additions and 1 deletions
+53
View File
@@ -0,0 +1,53 @@
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))
}