Source

GtugGoSandbox / goproj / positions / positions.go

package positions

import (
    "appengine"
    "appengine/user"
    "fmt"
    "http"
    "json"
    "rand"
)


type Position struct{
    Name string
    Location [2]float32
}

type Player struct{
    Name string
    Profession string
    Score int
}

type Result struct{
    player string
    hitpoint int
}

func init(){
    http.HandleFunc("/position/",handler)
    http.HandleFunc("/", defaultHandler)
}

func handler(w http.ResponseWriter,r *http.Request){
    c := appengine.NewContext(r)
    u := user.Current(c)
    if u == nil{
        url, err := user.LoginURL(c,r.URL.String())
        if err != nil{
            http.Error(w,err.String(),http.StatusInternalServerError)
            return
        }
        w.Header().Set("Location",url)
        w.WriteHeader(http.StatusFound)
        return
    }
    count := rand.Intn(30)
    parr := []Position{}
    for i := 1; i<=count; i++ {
        parr = append(parr,Position{u.String(),[2]float32{3.10593+rand.Float32(),101.66478+rand.Float32()}})
    }
    b,err := json.Marshal(parr)
    if err != nil{
        http.Error(w,err.String(),http.StatusInternalServerError)
        return
    }
    fmt.Fprint(w,string(b))
}

func action(w http.ResponseWriter,r *http.Request){
   c := appengine.NewContext(r)
   u := user.Current(c)
   hp := rand.Intn(10)
   player1 := Result{u.String(),hp}
   p2 := r.FormValue("opponent") 
   hp2 := rand.Intn(10)
   player2 := Result{p2,hp2}
   result_set := [2]Result{player1,player2}

   b,err := json.Marshal(result_set)
   if err != nil{
        http.Error(w,err.String(),http.StatusInternalServerError)
        return
    }
    fmt.Fprint(w,string(b))
}