Created
April 15, 2011 19:25
-
-
Save joseph-montanez/922304 to your computer and use it in GitHub Desktop.
valac -g --pkg libsoup-2.4 --pkg gee-1.0 --pkg gnet-2.0 --pkg json-glib-1.0 --save-temps --thread mywebapp.vala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyWebApp { | |
public Gee.HashMap<string, Json.Object> sessions; | |
public MyWebApp () | |
{ | |
this.sessions = new Gee.HashMap<string, Json.Object> (); | |
} | |
public string get_session_id (out unowned Soup.Message msg) | |
{ | |
Soup.Message msg2 = (owned) msg; | |
unowned Soup.MessageHeaders headers = msg2.response_headers; | |
unowned Soup.MessageHeaders request_headers = msg.request_headers; | |
string sid = ""; | |
request_headers.foreach ((key, name) => { | |
if (key == "Cookie") { | |
unowned Soup.Cookie parsedCookie = Soup.Cookie.parse ( | |
key + ": " + name, | |
new Soup.URI ("/") | |
); | |
if (parsedCookie.name == "sid") { | |
sid = parsedCookie.value; | |
} | |
} | |
}); | |
if (sid == "") { | |
// There is no session make one | |
sid = Random.int_range (1, 1000000).to_string (); | |
sid += new DateTime.now_local ().to_unix ().to_string (); | |
var hash = new GNet.MD5.buf (sid.to_utf8 ()); | |
//sha.update (sid.to_utf8 ()); | |
sid = hash.get_string (); | |
} | |
if (!this.sessions.has_key (sid)) { | |
this.sessions[sid] = new Json.Object (); | |
var cookie = new Soup.Cookie ("sid", sid, "127.0.0.1", "/", 12000); | |
headers.append("Set-Cookie", cookie.to_set_cookie_header ()); | |
} | |
return sid; | |
} | |
public void default_handler (Soup.Server server, Soup.Message msg, string path, | |
GLib.HashTable? query, Soup.ClientContext client) | |
{ | |
string sid = this.get_session_id (out msg); | |
string response_text = """ | |
<html> | |
<body> | |
<p>Comming Soon!</p> | |
</body> | |
</html>"""; | |
msg.set_response ("text/html", Soup.MemoryUse.COPY, | |
response_text.data); | |
} | |
public static int main(string[] args) { | |
var app = new MyWebApp (); | |
var server = new Soup.Server ( | |
Soup.SERVER_PORT, 8000 | |
); | |
server.add_handler ("/", app.default_handler); | |
stdout.printf("Running...\n"); | |
server.run (); | |
return 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment