Beispiel #1
0
//Genertor to generate a handler that loads a template and applies a Page loaded from json.
func GenJSONServer(root string) func(http.ResponseWriter, *http.Request) {

	return func(w http.ResponseWriter, req *http.Request) {
		filename := getFilename(req, "index")

		logger.Logf(1, "Serving document to %s: %s", req.RemoteAddr, filename)
		page, err := jsonLoadPage(root, filename)
		p := entity.GetPlayer(1337, "hunter02")

		if err == nil {

			page.ApplyPageTemplate(p)
			template, err := FileGet(root, "/template.html")

			if err != nil {
				Error(404, root, w, req)
				return
			}
			err = ApplyTemplate(w, page, template)

			if err != nil {
				Error(404, root, w, req)
				return
			}
		} else {
			logger.Logf(2, "Error: %s", err.Error())
			Error(404, root, w, req)
		}
	}
}
Beispiel #2
0
func init() {
	os.MkdirAll(*dataFolder+"/logs", 0666)
	var err error
	l, err = logger.NewFileLogger("meta")
	if err != nil {
		l = logger.NewLoggie("meta", os.Stdout)
		logger.Logf(logger.MINOR, "Could not open logfile: %s\n Continuing without logging to file.", err)
	}
	logger.Logf(0, "l: %v", l)
	l.SetLogLevel(logger.GetLogLevel(loglvl))
}
Beispiel #3
0
//Writes the slice to all registered connections.
func (net Network) Write(p []byte) (n int, err error) {
	for c := range net.conns {
		m, e := c.Write(p)
		n += m
		if e != nil {
			logger.Logf(5, "Error: %s", e)
			logger.Logf(6, "p: %s", string(p))
			go c.Close()
		}
	}
	return
}
// Blocking function that reads JSON objects from the connection and broadcasts them on the network.
func (wsc WSConnection) Reader() {
	for {
		var data interface{}
		err := websocket.JSON.Receive(wsc.connection, &data)
		logger.Logf(10, "Data from player: %d", wsc.p.Id)
		logger.Logf(10, "%v", data)
		wsc.n.world.broadcast <- &data
		if err != nil {
			logger.Logf(5, "Error on read: %s", err.Error())
			break
		}
	}
	go wsc.Close()
}
// Closes the connection and frees system resources connected to it.
func (wsc WSConnection) Close() {
	if wsc.online {
		wsc.online = false
		logger.Logf(5, "Closing connection to: %s", wsc.connection.RemoteAddr())
		wsc.connection.Close()
	}
}
Beispiel #6
0
//Generates a function that serves resources.
//Resources includes anything not html or plain text.
func GenResourceServer(root string) func(http.ResponseWriter, *http.Request) {
	return func(w http.ResponseWriter, req *http.Request) {
		filename := root + "/" + req.URL.Path[1:]
		logger.Logf(2, "Serving resource to %s: %s", req.RemoteAddr, filename)
		http.ServeFile(w, req, filename)
	}
}
// Goable blocking function that looks for messages on the channel and writes it in JSON format.
func (wsc WSConnection) Writer() {
	for message := range wsc.send {
		err := websocket.JSON.Send(wsc.connection, message)
		if err != nil {
			logger.Logf(5, "Error on write: %s", err.Error())
			break
		}
	}
}
Beispiel #8
0
/**
 * Based on the request, it loads a file into a buffer and returns it.
 * If the requested file ends with a / then index.html is appended.
 *
 */
func FileGet(root string, filename string) (b []byte, err error) {
	buf := bytes.NewBufferString("")
	logger.Logf(4, "Opening file: %s", root+filename)
	r, err := os.Open(root + filename)

	if err == nil {
		defer r.Close()
		defer func() {
			if r := recover(); r != nil {
				logger.Logf(1, "Panic while reading file: %s\n", filename)
				b = []byte("")
			}
		}()
		buf.ReadFrom(r)
	}
	b = buf.Bytes()
	return
}
Beispiel #9
0
func (sys *System) RunPhysics() {
	ticker := time.Tick(time.Second)
	var dt time.Duration = 0
	for t := range ticker {
		logger.Logf(logger.INFO, "Time since last physics update: %G ns", dt)
		//TODO DO MAGICAL PHYSICS STUFFS ON CHILDREN AND SHIPS.
		//WILL SOMEONE PLEASE THINK OF THE CHILDREN!?!?!?!?
		dt = time.Since(t)
	}
}
Beispiel #10
0
//Root server generates a function that serves html content from the root directory and all subdirectories except res/.
//That is the folder dedicated to resources and need special treatment.
//It loads a file from disk and treats it as a template and processes it based on the player object
//it gets from the GetPlayer(...) metod.
func GenRootServer(root string) func(http.ResponseWriter, *http.Request) {
	return func(w http.ResponseWriter, req *http.Request) {
		filename := getFilename(req, "index.html")

		logger.Logf(1, "Serving document to %s: %s", req.RemoteAddr, filename)

		b, err := FileGet(root, filename)
		if len(b) < 1 || err != nil {
			logger.Logf(5, "len(b): %d, err: %s", len(b), err)
			Error(404, root, w, req)
			return
		}

		p := entity.GetPlayer(1337, "hunter02")
		err = ApplyTemplate(w, p, b)
		if err != nil {
			logger.Logf(2, "Failed to apply template: %s", err)
			Error(404, root, w, req)
			return
		}
	}
}
Beispiel #11
0
func setVars(c config.Config) {
	root = c["root"]
	t, err := strconv.Atoi(c["port"])
	if err == nil {
		port = t
	} else {
		logger.Logf(logger.NORMAL, "Error while setting port to %v: %s", t, err.Error())
	}

	t, err = strconv.Atoi(c["wsport"])
	if err == nil {
		wsport = t
	} else {
		logger.Logf(logger.NORMAL, "Error while setting wsport to %v: %s", t, err.Error())
	}

	t, err = strconv.Atoi(c["loglevel"])
	if err == nil {
		loglvl = t
	} else {
		logger.Logf(logger.NORMAL, "Error while setting loglevel to %v: %s", t, err.Error())
	}
}
Beispiel #12
0
// Echo the data received on the Web Socket.
func GenNewConnectionHandeler(w *structures.World) func(*websocket.Conn) {
	logger.Log(5, "WS: Handlerfunction registered for the world!")
	return func(ws *websocket.Conn) {
		logger.Logf(3, "WS: Connection established from %s!", ws.RemoteAddr().String())
		n := getNetwork(w, ws)
		p := GetPlayer(ws)
		c := structures.NewWSConnection(p, n, ws, make(chan interface{}, 7))
		n.Register(c)
		defer func() { n.GetDisconnecting() <- c }()
		ws.Write(structures.NewAssignMessage(p))
		go c.Writer()
		c.Reader()
	}
}
Beispiel #13
0
func (c *CommandLine) ListenAndServe() {
	fmt.Println("For help using the commandline, use \"help\".")
	reader := bufio.NewReader(os.Stdin)

	var line string
	var cmd *command
	for !c.stop {
		c.printPrompt()
		line = readLine(reader)
		input := strings.Split(line, " ")

		cmd = c.ComMap[input[0]]
		if cmd != nil {
			logger.Logf(1, "Console used command: %s", line)
			cmd.function(input[1:])
		} else {
			c.printHelp()
		}
	}
	fmt.Println("End of the line! All passangers, prepare for landing!")
	c.exit <- true
}
Beispiel #14
0
//Adds a new connection to the network.
func (net Network) Register(c Connection) {
	net.conns[c] = true
	logger.Logf(6, "net.conns: %v", net.conns)
}
Beispiel #15
0
func Error(code int, root string, w http.ResponseWriter, req *http.Request) {
	filename := fmt.Sprintf("%s/%d.html", root, code)
	logger.Logf(3, "Serving Error to %s: %s", req.RemoteAddr, filename)
	http.ServeFile(w, req, filename)
	//w.Write([]byte(E404TEXT))
}