Skip to content

Instantly share code, notes, and snippets.

@dyoder
Created March 6, 2012 04:55
Show Gist options
  • Save dyoder/1983681 to your computer and use it in GitHub Desktop.
Save dyoder/1983681 to your computer and use it in GitHub Desktop.
Go dispatcher, phase 1
http = require('http')
Redis = require("redis")
c = Redis.createClient(@port, @host)
marshal = (req) ->
JSON.stringify
method: req.method
url: req.url
headers: req.headers
body: req.body
count = 0
(http.createServer (req, res) ->
body = ''
req.on 'data', (data) -> body += data
req.on 'end', () ->
req.body = body
c.set count.toString(),marshal(req), (err) ->
if err
console.log err
process.exit -1
res.writeHead 200,
'Content-Type': 'text/plain'
res.end('Hello World\n')
count++
).listen(1337, "127.0.0.1");
package main
import (
"os"
"fmt"
"encoding/json"
"net/http"
"github.com/simonz05/godis"
)
var c *godis.Client
var count int
func set(key string, val string) {
if err := c.Set(key,val); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func handler(w http.ResponseWriter, r *http.Request) {
// we'll await a response on this channel
ch := make(chan int)
// marshal the request
bytes,err := json.Marshal(r)
if err!= nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
go func() {
// add the request to redis
set(fmt.Sprint(count),fmt.Sprintf("%s",bytes))
// increment the "request id"
count += 1
// okay, faking the response
ch <- 1
}()
// wait for the response
<-ch
// send as HTTP
w.Header().Set("Content-Type","text/plain")
fmt.Fprint(w,"Hello world\n")
}
func main() {
c = godis.New("", 0, "")
count = 0
http.HandleFunc("/", handler)
http.ListenAndServe(":3000", nil)
}
{
"Method": "GET",
"URL": {
"Scheme": "",
"Opaque": "",
"User": null,
"Host": "",
"Path": "\/",
"RawQuery": "",
"Fragment": ""
},
"Proto": "HTTP\/1.1",
"ProtoMajor": 1,
"ProtoMinor": 1,
"Header": {
"Accept": [
"*\/*"
],
"User-Agent": [
"curl\/7.20.0 (i386-apple-darwin10.2.0) libcurl\/7.20.0 OpenSSL\/0.9.8n zlib\/1.2.4 libidn\/1.16"
]
},
"Body": {
},
"ContentLength": 0,
"TransferEncoding": null,
"Close": false,
"Host": "localhost:3000",
"Form": null,
"MultipartForm": null,
"Trailer": null,
"RemoteAddr": "127.0.0.1:64001",
"RequestURI": "\/",
"TLS": null
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment