Skip to content

Instantly share code, notes, and snippets.

@MarcoPolo
Last active December 19, 2015 14:49
Show Gist options
  • Save MarcoPolo/5972384 to your computer and use it in GitHub Desktop.
Save MarcoPolo/5972384 to your computer and use it in GitHub Desktop.
My first go
//My first Go program w/o any internet access
package main
import (
"net/http"
"fmt"
)
type Game struct {
Choice string
Ch chan *ChoiceWrap
}
type ChoiceWrap struct {
Choice string
Result chan string
}
func (g Game) ServeHTTP(
w http.ResponseWriter,
r *http.Request) {
//Send the choice to the choice channel so it can be read by the other goroutine
boolChan := make(chan bool)
g.Ch <- &ChoiceWrap{g.Choice, boolChan}
fmt.Fprint(w, <-boolChan)
}
func didFirstOneWin(c chan *ChoiceWrap){
for {
oneWrap, twoWrap := <-c, <-c
one, two := oneWrap.Choice, twoWrap.Choice
fmt.Println("got",one,two)
if (one=="rock" && two=="scissors") ||
(one=="paper" && two=="rock") ||
(one=="scissors" && two == "paper") {
oneWrap.Result <- "You won :)"
twoWrap.Result <- "You lost :("
}else if one==two {
oneWrap.Result <- "You lost :("
twoWrap.Result <- "You lost :("
}else {
oneWrap.Result <- "You lost :("
twoWrap.Result <- "You won :)"
}
}
}
func main() {
c := make(chan *ChoiceWrap, 2)
go http.Handle("/rock", &Game{"rock", c})
go http.Handle("/paper", &Game{"paper",c})
go http.Handle("/scissors", &Game{"scissors", c})
//continously read the channel to see if something a choice has updated
go didFirstOneWin(c)
// your http.Handle calls here
http.ListenAndServe("localhost:4000", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment