Skip to content

Instantly share code, notes, and snippets.

@dearing
Created March 22, 2012 03:55
Show Gist options
  • Save dearing/2155700 to your computer and use it in GitHub Desktop.
Save dearing/2155700 to your computer and use it in GitHub Desktop.
GO, FizzBuzz as a webserver...
/*
FizzBuzz in GO, as a webserver...
*/
package main
import (
"flag"
"fmt"
"net/http"
c "strconv"
"text/template"
)
var num int
var index = template.Must(template.ParseFiles("index.html"))
var fresh = template.Must(template.ParseFiles("fizzbuzz.html"))
func main() {
flag.IntVar(&num, "index", 0, "numeric index")
host := flag.String("host", ":8008", "host to bind to")
flag.Parse()
http.HandleFunc("/", indexHandler)
http.HandleFunc("/fizzbuzz", fizzbuzzHandler)
fmt.Printf("listening on %s with index %d\r\n", *host, num)
http.ListenAndServe(*host, nil)
}
func indexHandler(res http.ResponseWriter, req *http.Request) {
err := index.Execute(res, num)
if err != nil {
res.Write([]byte("<big>BALLS!</big>"))
}
}
func fizzbuzzHandler(res http.ResponseWriter, req *http.Request) {
num++
err := fresh.Execute(res, fizzbuzz(num))
if err != nil {
res.Write([]byte("<i>SUCK!/i>"))
}
}
func fizzbuzz(hc int) (g string) {
if hc%5 == 0 && hc%3 == 0 {
return ("FizzBuzz")
}
if hc%5 == 0 {
return ("Buzz")
}
if hc%3 == 0 {
return ("Fizz")
}
// int to string?
// 'dogs and cats living together...'
return c.Itoa(hc)
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>FizzBuzz on da WEB</title>
<style type="text/css">
body
{
overflow: hidden;
padding: 0;
margin: 4em;
width: 100%;
height: 100%;
background: black;
color:white;
font-size:3em;
}
a:link,a:visited,a:active,a:hover
{
color:white;
text-decoration:none
}
</style>
</head>
<body>
<h1><a href='/fizzbuzz'>{{.}}</a></h1>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>FizzBuzz on da WEB</title>
<style type="text/css">
body
{
overflow: hidden;
padding: 0;
margin: 4em;
width: 100%;
height: 100%;
background: black;
color:white;
font-size:3em;
}
a:link,a:visited,a:active,a:hover
{
color:white;
text-decoration:none
}
</style>
</head>
<body>
<h1><a href='/fizzbuzz'> fizzbuzz@{{.}}</a></h1>
</body>
</html>
@dearing
Copy link
Author

dearing commented Mar 22, 2012

go version weekly.2012-03-13 +87d50a70f7d2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment