You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-sendxmpp/helpers.go

74 lines
1.3 KiB
Go

// Copyright Martin Dosch.
// Use of this source code is governed by the BSD-2-clause
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"crypto/rand"
"fmt"
"log"
"net/url"
"os"
"regexp"
"strings"
)
func validUTF8(s string) string {
// Remove invalid code points.
s = strings.ToValidUTF8(s, "")
reg := regexp.MustCompile(`[\x{0000}-\x{0008}\x{000B}\x{000C}\x{000E}-\x{001F}]`)
s = reg.ReplaceAllString(s, "")
return s
}
func validURI(s string) (*url.URL, error) {
// Check if URI is valid
uri, err := url.ParseRequestURI(s)
return uri, err
}
func readFile(path string) (*bytes.Buffer, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
buffer := new(bytes.Buffer)
_, err = buffer.ReadFrom(file)
if err != nil {
return nil, err
}
return buffer, nil
}
func getRpad(messageLength int) string {
length := 100 - messageLength%100
rpad := make([]byte, length)
_, err := rand.Read(rpad)
if err != nil {
log.Fatal(err)
}
return fmt.Sprintf("%x", rpad)
}
func getID() string {
id := make([]byte, 12)
_, err := rand.Read(id)
if err != nil {
log.Fatal(err)
}
return fmt.Sprintf("%x-%x-%x", id[0:4], id[4:8], id[8:])
}
func getShortID() string {
id := make([]byte, 4)
_, err := rand.Read(id)
if err != nil {
log.Fatal(err)
}
return fmt.Sprintf("%x", id[0:4])
}