Skip to content

Instantly share code, notes, and snippets.

@Philio
Created August 10, 2015 10:00
Show Gist options
  • Save Philio/1ad74990f50cf114098b to your computer and use it in GitHub Desktop.
Save Philio/1ad74990f50cf114098b to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"os"
"net"
"bufio"
"encoding/json"
bcap "github.com/fromYukki/browscap_go"
)
const bcapFile = "browscap.ini"
const socket = "server.sock"
var errorJson []byte = []byte("{\"error\":\"Something went wrong\"}")
func handleConnection(conn net.Conn, requestNumber int64) {
var err error
var res []byte
line, err := bufio.NewReader(conn).ReadString('\n')
if err != nil {
panic(err)
}
browser, ok := bcap.GetBrowser(line)
if !ok || browser == nil {
res = errorJson
} else {
res, err = json.Marshal(browser)
if err != nil {
panic(err)
}
}
conn.Write(res)
conn.Close()
fmt.Printf("\nRequest #%d: %s", requestNumber, line)
fmt.Println("Response: ", string(res))
}
func exists() bool {
if _, err := os.Stat(bcapFile); err == nil {
return true
}
return false
}
func main() {
if !exists() {
fmt.Println("Downloading ", bcapFile)
err := bcap.DownloadFile(bcapFile)
if err != nil {
panic(err)
}
}
fmt.Println("Initialising")
if err := bcap.InitBrowsCap(bcapFile, false); err != nil {
panic(err)
}
os.Remove(socket)
ln, err := net.Listen("unix", socket)
if err != nil {
panic(err)
}
defer ln.Close()
fmt.Println("Listening for connections")
var requests int64 = 0;
for {
conn, err := ln.Accept()
if err != nil {
panic(err)
}
requests ++
go handleConnection(conn, requests)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment