diff options
Diffstat (limited to 'app/utilities.go')
| -rw-r--r-- | app/utilities.go | 115 |
1 files changed, 115 insertions, 0 deletions
diff --git a/app/utilities.go b/app/utilities.go new file mode 100644 index 0000000..65a6716 --- /dev/null +++ b/app/utilities.go @@ -0,0 +1,115 @@ +package main + +import ( + "bytes" + "crypto/md5" + "encoding/gob" + "errors" + "fmt" + "github.com/garyburd/redigo/redis" + "golang.org/x/crypto/bcrypt" + // "html/template" + "io" + "io/ioutil" + "log" + "math/rand" + "net/http" + "os" + "time" +) + +// Returns the response from a GET request plus the headers as map and the content as string +func HttpGet(url string) (*http.Response, string, error) { + r, err := http.Get(url) + if err != nil { + return r, "Get request failed.", err + } + + defer r.Body.Close() + contents, err := ioutil.ReadAll(r.Body) + if err != nil { + return r, "Reading body failed.", err + } + + return r, string(contents), nil +} + +// Hashs and returns a string (md5) +func Md5Hash(content string) string { + h := md5.New() + io.WriteString(h, content) + hash := fmt.Sprintf("%x", h.Sum(nil)) + + return hash +} + +// Creates a random string +func RandomKey() string { + rand.Seed(time.Now().UTC().UnixNano()) + letters := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") + key := make([]rune, 40) + for i := range key { + key[i] = letters[rand.Intn(len(letters))] + } + + return string(key) +} + +var pool = newPool() + +// Creates a pool with connections to Redis +func newPool() *redis.Pool { + return &redis.Pool{ + MaxIdle: 3, + IdleTimeout: 240 * time.Second, + Dial: func() (redis.Conn, error) { + redis_server := os.Getenv("STATUS_REDIS_SERVER") + redis_port := os.Getenv("STATUS_REDIS_PORT") + c, err := redis.Dial("tcp", redis_server+":"+redis_port) + if err != nil { + return nil, err + } + return c, err + }, + TestOnBorrow: func(c redis.Conn, t time.Time) error { + _, err := c.Do("PING") + return err + }, + } +} + +// Hashs password with bcrypt and returns the string +func HashPassword(password string) (string, error) { + if password == "" { + return "", errors.New("Empty password.") + } + p := []byte(password) + hash, err := bcrypt.GenerateFromPassword(p, 10) + if err != nil { + return "", err + } + return string(hash), nil +} + +// Verify password and hash +func VerifyPassword(password, hash string) bool { + if hash == "" || password == "" { + return false + } + err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) + if err != nil { + log.Printf("%s \n", err) + return false + } + return true +} + +func GetBytes(key interface{}) ([]byte, error) { + var buf bytes.Buffer + enc := gob.NewEncoder(&buf) + err := enc.Encode(key) + if err != nil { + return nil, err + } + return buf.Bytes(), nil +} |
