github.com/cellofellow/gopkg@v0.0.0-20140722061823-eec0544a62ad/web/helpers.go (about)

     1  // Copyright 2013 <chaishushan{AT}gmail.com>. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package web
     6  
     7  import (
     8  	"bytes"
     9  	"encoding/base64"
    10  	"errors"
    11  	"net/http"
    12  	"net/url"
    13  	"os"
    14  	"regexp"
    15  	"strings"
    16  	"time"
    17  )
    18  
    19  // internal utility methods
    20  func webTime(t time.Time) string {
    21  	ftime := t.Format(time.RFC1123)
    22  	if strings.HasSuffix(ftime, "UTC") {
    23  		ftime = ftime[0:len(ftime)-3] + "GMT"
    24  	}
    25  	return ftime
    26  }
    27  
    28  func dirExists(dir string) bool {
    29  	d, e := os.Stat(dir)
    30  	switch {
    31  	case e != nil:
    32  		return false
    33  	case !d.IsDir():
    34  		return false
    35  	}
    36  
    37  	return true
    38  }
    39  
    40  func fileExists(dir string) bool {
    41  	info, err := os.Stat(dir)
    42  	if err != nil {
    43  		return false
    44  	}
    45  
    46  	return !info.IsDir()
    47  }
    48  
    49  // Urlencode is a helper method that converts a map into URL-encoded form data.
    50  // It is a useful when constructing HTTP POST requests.
    51  func Urlencode(data map[string]string) string {
    52  	var buf bytes.Buffer
    53  	for k, v := range data {
    54  		buf.WriteString(url.QueryEscape(k))
    55  		buf.WriteByte('=')
    56  		buf.WriteString(url.QueryEscape(v))
    57  		buf.WriteByte('&')
    58  	}
    59  	s := buf.String()
    60  	return s[0 : len(s)-1]
    61  }
    62  
    63  var slugRegex = regexp.MustCompile(`(?i:[^a-z0-9\-_])`)
    64  
    65  // Slug is a helper function that returns the URL slug for string s.
    66  // It's used to return clean, URL-friendly strings that can be
    67  // used in routing.
    68  func Slug(s string, sep string) string {
    69  	if s == "" {
    70  		return ""
    71  	}
    72  	slug := slugRegex.ReplaceAllString(s, sep)
    73  	if slug == "" {
    74  		return ""
    75  	}
    76  	quoted := regexp.QuoteMeta(sep)
    77  	sepRegex := regexp.MustCompile("(" + quoted + "){2,}")
    78  	slug = sepRegex.ReplaceAllString(slug, sep)
    79  	sepEnds := regexp.MustCompile("^" + quoted + "|" + quoted + "$")
    80  	slug = sepEnds.ReplaceAllString(slug, "")
    81  	return strings.ToLower(slug)
    82  }
    83  
    84  // NewCookie is a helper method that returns a new http.Cookie object.
    85  // Duration is specified in seconds. If the duration is zero, the cookie is permanent.
    86  // This can be used in conjunction with ctx.SetCookie.
    87  func NewCookie(name string, value string, age int64) *http.Cookie {
    88  	var utctime time.Time
    89  	if age == 0 {
    90  		// 2^31 - 1 seconds (roughly 2038)
    91  		utctime = time.Unix(2147483647, 0)
    92  	} else {
    93  		utctime = time.Unix(time.Now().Unix()+age, 0)
    94  	}
    95  	return &http.Cookie{Name: name, Value: value, Expires: utctime}
    96  }
    97  
    98  // GetBasicAuth is a helper method of *Context that returns the decoded
    99  // user and password from the *Context's authorization header
   100  func (ctx *Context) GetBasicAuth() (string, string, error) {
   101  	authHeader := ctx.Request.Header["Authorization"][0]
   102  	authString := strings.Split(string(authHeader), " ")
   103  	if authString[0] != "Basic" {
   104  		return "", "", errors.New("Not Basic Authentication")
   105  	}
   106  	decodedAuth, err := base64.StdEncoding.DecodeString(authString[1])
   107  	if err != nil {
   108  		return "", "", err
   109  	}
   110  	authSlice := strings.Split(string(decodedAuth), ":")
   111  	if len(authSlice) != 2 {
   112  		return "", "", errors.New("Error delimiting authString into username/password. Malformed input: " + authString[1])
   113  	}
   114  	return authSlice[0], authSlice[1], nil
   115  }