Last active
January 17, 2018 16:59
-
-
Save rimusz/7c37033f6226c7936abb49e680d6daf8 to your computer and use it in GitHub Desktop.
This file contains hidden or 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" | |
"os" | |
) | |
var beersPage = `<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Beer demo</title> | |
</head> | |
<body> | |
<h1>{{.BeerName}}</h1> | |
<h2>{{.BeerStyle}}</h2> | |
<p>{{.BeerDescription}}</p> | |
</body> | |
</html>` | |
type Beer struct { | |
BeerName string | |
BeerStyle string | |
BeerDescription string | |
} | |
func handler(w http.ResponseWriter, r *http.Request) { | |
beer_url := os.Getenv("BEER_URL") | |
res, err := http.Get(beer_url) | |
if err != nil { | |
http.Error(w, err.Error(), 500) | |
return | |
} | |
defer res.Body.Close() | |
b := &Beer{} | |
// decoding request body | |
if err := json.NewDecoder(res.Body).Decode(b); err != nil { | |
http.Error(w, err.Error(), 500) | |
return | |
} | |
tmpl, err := template.New("beers").Parse(beersPage) | |
if err != nil { | |
http.Error(w, err.Error(), 500) | |
return | |
} | |
err = tmpl.Execute(w, b) | |
if err != nil { | |
http.Error(w, err.Error(), 500) | |
return | |
} | |
} | |
func main() { | |
http.HandleFunc("/", handler) | |
fmt.Println("Listening on: http://localhost:8080") | |
http.ListenAndServe(":8080", nil) | |
} |
rusenask
commented
Jan 17, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment