Last active
October 5, 2022 16:07
-
-
Save minusworld/62d30f299072bc6c0979778f4c00242f to your computer and use it in GitHub Desktop.
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 ( | |
"fmt" | |
"log" | |
"net/http" | |
) | |
func getMovieQuote() map[string]string { | |
m := make(map[string]string) | |
m["quote"] = "I'll be back." | |
m["movie"] = "The Terminator" | |
m["year"] = "1984" | |
return m | |
} | |
func healthCheck(w http.ResponseWriter, r *http.Request) { | |
// This is OK | |
w.Write([]byte("alive")) | |
} | |
func indexPage(w http.ResponseWriter, r *http.Request) { | |
const tme = `<html>` | |
const template = ` | |
<html> | |
<body> | |
<h1>Random Movie Quotes</h1> | |
<h2>%s</h2> | |
<h4>~%s, %s</h4> | |
</body> | |
</html>` | |
quote := getMovieQuote() | |
quoteText := quote["quote"] | |
movie := quote["movie"] | |
year := quote["year"] | |
w.WriteHeader(http.StatusAccepted) | |
// Should never use a format string for a template and | |
// directly write to the ResponseWriter. This bypasses | |
// HTML escaping. Always use "html/template" and | |
// the "template.Execute()" family of functions. | |
w.Write([]byte(fmt.Sprintf(template, quoteText, movie, year))) | |
} | |
func errorPage(w http.ResponseWriter, r *http.Request) { | |
params := r.URL.Query() | |
urls, ok := params["url"] | |
if !ok { | |
log.Println("Error") | |
return | |
} | |
url := urls[0] | |
const template = ` | |
<html> | |
<body> | |
<h1>error; page not found. <a href="%s">go back</a></h1> | |
</body> | |
</html>` | |
w.WriteHeader(http.StatusAccepted) | |
// Should never use a format string for a template and | |
// directly write to the ResponseWriter. This bypasses | |
// HTML escaping. Always use "html/template" and | |
// the "template.Execute()" family of functions. | |
w.Write([]byte(fmt.Sprintf(template, url))) | |
} | |
func main() { | |
http.HandleFunc("/", indexPage) | |
http.HandleFunc("/error", errorPage) | |
http.ListenAndServe(":8080", nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment