Beispiel #1
0
func gamepage(w http.ResponseWriter, r *http.Request) {
    cookie, _ := r.Cookie("Spanzhash")
    if(hashExists(cookie.Name))
	data, err := ioutil.ReadFile("./layouts/gamepage.html")
    if err==nil {
    	w.Header().Add("Content-Type","text/html")
    	w.Write(data)
    } else {
    	w.WriteHeader(404)
    	w.Write([]byte("404 Page not found - "+http.StatusText(404)))
    }
}
Beispiel #2
0
func HandlePing(c web.C, w http.Responsewriter, r *http.Request) {
	decoder := json.NewDecoder(r.Body)
	ping := &Ping{}
	err := decoder.Decode(ping)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		w.Write("Malformed Body")
		return
	}
	ping.Timestamp = time.Now()
	ping.NextPing = time.Now().Add(15*time.Minute)
	// Begin validation of different fields.
	if ping.Timestamp
}
Beispiel #3
0
func HomeHandler(w http.ResponseWriter, r *http.Request) {
	data, _ := json.Marshal([]string{"San Francisco", "Amsterdam",
	"Berlin","Palo Alto", "Los Altos})
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.Write(data)
}

func main() {
	http.HandleFunc("/", HomeHandler)
	err := http.ListenAndServe(":"+os.Getenv("PORT"), nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
Beispiel #4
0
func writingspaceHandler(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "GET":
		log.Println("GET")
		if err := 引擎.ExecuteTemplate(w, "writingspace", nil); err != nil {
			log.Fatalln(err.Error())
		}
	case "POST":
		data, _ := ioutil.ReadAll(r.Body)
		datastr := string(data)
		log.Printf(datastr)
		datastr = "{\"createtime\":\"" + StringHelper.Substr(time.Now().String(), 0, 19) + "\",\"text\":" + datastr + "}"
		log.Println(datastr)
		MongoHelper.Insert("test", "article", datastr)
		w.Write([]byte(""))
	}
}
Beispiel #5
0
func (play playerController) Create(rw http.ResponseWriter, req *http.Request) {
	body, err := ioutil.ReadAll(req.Body)

	var p models.Player

	if err != nil {
		panic(err)
	}
	err = json.Unmarshal(body, &p)
	if err != nil {
		panic(err)
	}

	db, err := sql.Open("postgres", "password=password host=localhost dbname=scrabble_dev sslmode=disable")
	if err != nil {
		log.Fatal(err)
	}
	players, err := db.Exec("CREATE TABLE IF NOT EXISTS players ( player1_name varchar(255), player1_score int DEFAULT 0, player2_name varchar(255), player2_score int DEFAULT 0)")
	if err != nil && players == nil {
		log.Fatal(err)
	}

	if p.Player1_name == "" || p.Player2_name == "" {
		b, err := json.Marshal(models.Error{
			Success: "false",
			Error:   "Players name are required",
		})
		if err != nil {
			log.Fatal(err)
		}
		rw.Header().Set("Content-Type", "application/json")
		rw.Write(b)
		goto end
	} else if p.Player1_name == p.Player2_name {
		b, err := json.Marshal(models.Error{
			Success: "false",
			Error:   "Players name cant be same",
		})
		if err != nil {
			log.Fatal(err)
		}
		rw.Header().Set("Content-Type", "application/json")
		rw.Write(b)
		goto end
	} else {
		player_exist, err := db.Query("SELECT player1_name, player2_name FROM players")
		if err != nil {
			log.Fatal(err)
		}

		for player_exist.Next() {
			var player1 string
			var player2 string

			err := player_exist.Scan(&player1, &player2)
			if err != nil {
				log.Fatal(err)
			}
			b, err := json.Marshal(models.Error{
				Success: "false",
				Error:   "Player names already exist",
			})
			if err != nil {
				log.Fatal(err)
			}
			rw.Header().Set("Content-Type", "application/json")
			rw.Write(b)
			goto end
		}
		var Stmt string = "insert into players ( player1_name,Player2_name ) values($1,$2)"
		stmt, err := db.Prepare(Stmt)
		if err != nil {
			log.Fatal(err)
		}
		result, err := stmt.Exec(p.Player1_name, p.Player2_name)
		if err != nil || result == nil {
			log.Fatal(err)
		}
		b, err := json.Marshal(models.Message{
			Success: "true",
			Message: "Game Begins!",
		})
		if err != nil {
			log.Fatal(err)
		}
		rw.Header().Set("Content-Type", "application/json")
		rw.Write(b)
		goto end
	}
end:
}
Beispiel #6
0
//处理单独的Http请求
func (this *HttpService) HandleHttp(w http.ResponseWriter, req *http.Request) {
	req.ParseForm()
	uid := req.Header.Get(Sec_Auth_Uid)
	key := req.Header.Get(Sec_Auth_Key)
	c := this.getClient(uid, key)
	defer c.Close()

	if data := req.FormValue("json"); len(data) > 0 {
		cmd := new(common.RequestData)
		c.Read([]byte(data), cmd)
		protocol.Exec(cmd, &c.Client)
	} else {
		cmd := common.ResponseData{0, -1, "json string is empty", ""}
		c.Send(&cmd)
	}
	for {
		timeout := time.After(time.Nanosecond * 10) //10ns就超时
		select {
		case data := <-c.OutputChan:
			if _, err := w.Write(data); err != nil {
				log.Error("%s send cmd error and login out,%s\n", c.Name, err.Error())
			}
			break
		case <-timeout:
			goto end
		}
	}
end:
}

//按cookei取在线用户
func (this *HttpService) getClient(uid string, key string) *HttpClient {
	c := new(HttpClient)
	if s, _, ok := online.GetSession(uid); ok && s == key { //key相同时认为已登陆过的
		if tc, ok := online.Get(uid); ok { //第一个登陆的Client的uuid被当作了uid
			c.Name = tc.Name
			c.IsLogin = tc.IsLogin
			c.IsPlayBack = c.IsPlayBack
		}
	}
	if c == nil {
		c = new(HttpClient)
	}
	c.UUID = uuid.New()
	c.IsRun = true
	c.OutputChan = make(chan []byte, 10)
	return c
}

////设置cookie
//func (this *HttpService) setCookie(c *HttpClient, w http.ResponseWriter, age int) {
//	id := &http.Cookie{Name: "monitor_http_key", Value: common.HashString(c.Name + ":monitor"), Path: "/", MaxAge: age, HttpOnly: true, Secure: true}
//	name := &http.Cookie{Name: "monitor_http_name", Value: c.Name, Path: "/", MaxAge: age, HttpOnly: true, Secure: true}
//	http.SetCookie(w, id)
//	http.SetCookie(w, name)
//}

//处理Socket请求
func (this *HttpService) HandleSocket(ws *websocket.Conn) {
	connFrom := ws.RemoteAddr()
	log.Infof("accept new http client from %s\n", connFrom)
	uid := ws.Request().Header.Get(Sec_Auth_Uid)
	key := ws.Request().Header.Get(Sec_Auth_Key)
	c := this.getClient(uid, key)
	c.Connect = ws
	go this.HandleResponse(c)
	this.HandleRequest(c)
}

//主运行方法
//根目录为标准Http请求
//socket为Socket请求
func (this *HttpService) Run() {
	this.IsRun = true
	http.Handle("/", http.FileServer(http.Dir("."))) // <-- note this line
	http.HandleFunc("/http", this.HandleHttp)
	http.Handle("/socket", websocket.Handler(this.HandleSocket))
	log.Infof("http service started at %s:%d", this.Host, this.Port)
	log.Info("http socket host on /http and /socket ")
	if err := http.ListenAndServe(fmt.Sprintf("%s:%d", this.Host, this.Port), nil); err != nil {
		log.Error("http service start error", err.Error())
	}
}

//send cmd to client
func (this *HttpService) HandleResponse(c *HttpClient) {
	var err error
	defer online.Delete(c.UUID)
	for cmd := range c.OutputChan {
		//cmd := <-c.OutputChan
		cmd = append(cmd, '\n')
		if err = websocket.Message.Send(c.Connect, string(cmd)); err != nil {
			log.Error("%s send cmd error and login out,%s\n", c.Name, err.Error())
			c.IsRun = false
			break
		}
		c.UpdateTime()
	}
}

//handle tcp request
func (this *HttpService) HandleRequest(c *HttpClient) {
	var err error
	defer online.Delete(c.UUID)
	cmd := new(common.RequestData)
	var data []byte
	for this.IsRun && c.IsRun {
		if err = websocket.Message.Receive(c.Connect, &data); err != nil {
			log.Infof("%s can't received cmd", c.Name, err.Error())
			c.IsRun = false
			break
		}
		c.Read(data, cmd)
		protocol.Exec(cmd, &c.Client)
		c.UpdateTime()
	}
}