Skip to content

Instantly share code, notes, and snippets.

@martin-helmich
Created July 1, 2017 11:01
Show Gist options
  • Save martin-helmich/e01bc711f953f4901d3c7a4a1c970040 to your computer and use it in GitHub Desktop.
Save martin-helmich/e01bc711f953f4901d3c7a4a1c970040 to your computer and use it in GitHub Desktop.
Web development with Go; Minimal example
package main
import (
"encoding/json"
"fmt"
"html/template"
"net/http"
)
type User struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Email string `json:"email"`
}
var users = []User{
{"Martin", "Helmich", "martin@example.com"},
{"Max", "Mustermann", "max@example.com"},
}
func main() {
http.HandleFunc("/users.json", func(res http.ResponseWriter, req *http.Request) {
res.Header().Set("Content-Type", "application/json;charset=utf-8")
json.NewEncoder(res).Encode(users)
})
http.HandleFunc("/users.html", func(res http.ResponseWriter, req *http.Request) {
t, err := template.ParseFiles("userlist.html")
if err != nil {
res.WriteHeader(500)
fmt.Fprintf(res, "Fehler beim Laden des Templates: %s", err)
} else {
t.Execute(res, users)
}
})
http.ListenAndServe(":8080", nil)
}
<h1>Nutzer</h1>
<ul>
{{ range . }}
<li><a href="mailto:{{ .Email }}">{{ .FirstName }} {{ .LastName }}</a></li>
{{ end }}
</ul>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment