Created
July 1, 2017 11:01
-
-
Save martin-helmich/e01bc711f953f4901d3c7a4a1c970040 to your computer and use it in GitHub Desktop.
Web development with Go; Minimal example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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