hugo/helpers/general.go

111 lines
2.6 KiB
Go
Raw Normal View History

// Copyright © 2014 Steve Francia <spf@spf13.com>.
//
// Licensed under the Simple Public License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://opensource.org/licenses/Simple-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package helpers
import (
"bytes"
"crypto/md5"
"encoding/hex"
"fmt"
"io"
"net"
"path/filepath"
"strings"
)
2014-12-11 20:57:25 +00:00
//Filepath separator defined by os.Separator.
const FilePathSeparator = string(filepath.Separator)
func FindAvailablePort() (*net.TCPAddr, error) {
l, err := net.Listen("tcp", ":0")
if err == nil {
defer l.Close()
addr := l.Addr()
if a, ok := addr.(*net.TCPAddr); ok {
return a, nil
}
return nil, fmt.Errorf("Unable to obtain a valid tcp port. %v", addr)
}
return nil, err
}
2014-12-11 20:57:25 +00:00
// InStringArray checks if a string is an element of a slice of strings and returns a boolean value.
2014-10-21 00:15:33 +00:00
func InStringArray(arr []string, el string) bool {
for _, v := range arr {
if v == el {
return true
}
}
return false
}
2014-12-11 20:57:25 +00:00
// GuessType attempts to guess the type of file from a given string.
func GuessType(in string) string {
switch strings.ToLower(in) {
case "md", "markdown", "mdown":
return "markdown"
case "rst":
return "rst"
case "html", "htm":
return "html"
}
return "unknown"
}
2014-12-12 02:57:22 +00:00
//ReaderToBytes takes an io.Reader argument, reads from it and returns bytes.
func ReaderToBytes(lines io.Reader) []byte {
b := new(bytes.Buffer)
b.ReadFrom(lines)
return b.Bytes()
}
2014-12-12 02:57:22 +00:00
//ReaderToString is the same as ReaderToBytes, but returns a string.
func ReaderToString(lines io.Reader) string {
b := new(bytes.Buffer)
b.ReadFrom(lines)
return b.String()
}
2014-12-12 02:57:22 +00:00
//StringToReader does the opposite of ReaderToString.
func StringToReader(in string) io.Reader {
return strings.NewReader(in)
}
2014-12-12 02:57:22 +00:00
//BytesToReader does the opposite of ReaderToBytes.
func BytesToReader(in []byte) io.Reader {
return bytes.NewReader(in)
}
// sliceToLower goes through the source slice and lowers all values.
func SliceToLower(s []string) []string {
if s == nil {
return nil
}
l := make([]string, len(s))
for i, v := range s {
l[i] = strings.ToLower(v)
}
return l
}
2014-12-12 02:57:22 +00:00
//Md5String takes a string and returns a MD5 Hash of it.
func Md5String(f string) string {
h := md5.New()
h.Write([]byte(f))
return hex.EncodeToString(h.Sum([]byte{}))
}