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.

81 lines
1.9 KiB
Go

package shrt
import (
//"github.com/asaskevich/govalidator"
"fmt"
"crypto/sha256"
"errors"
"io"
"bytes"
)
type Storage struct {
Token map[string]string `json: tokens`
Url map[string]shrt `json: urls`
}
type shrt struct {
URL string
Token string
count int
}
var (
ErrNotFound = errors.New("Url not Found")
ErrCreateToken = errors.New("There are some problems while creating Token")
)
func Open() (*Storage, error){
// Open db ore create if not exist!
s := Storage{Token: make(map[string]string), Url: make(map[string]shrt)}
return &s, nil
}
func StreamToByte(stream io.Reader) []byte {
buf := new(bytes.Buffer)
buf.ReadFrom(stream)
return buf.Bytes()
}
func (s *Storage) Add(URL string, value interface{}) (string, error) {
// if the URL a valid URL?
/*if !govalidator.IsURL(URL) {
return "", errors.New("invalid url")
} */
// Create a sha256 Hash from the URL
hash := fmt.Sprintf("%x", sha256.Sum256([]byte(URL)))
// Test if the URL alraedy exist and return the key
if val, ok := s.Url[hash]; ok {
return val.Token, nil
}
// Iterate to the length of hash to get the shortest output
for hashShortestLen := 1; hashShortestLen <= 32; hashShortestLen++ {
// Test if the Token not exist and return the new generated token
if _, ok := s.Token[hash[:hashShortestLen]]; !ok {
token := hash[:hashShortestLen]
s.Token[token] = hash
s.Url[hash] = shrt{URL: URL, Token: token}
value = s.Url[hash]
return token, nil
}
}
return "", ErrCreateToken
}
func (s *Storage) Remove(URL string) error {
return nil
}
// Get returns the URL for the given token
func (s *Storage) Get(token string, value interface{}) bool {
if hash, ok := s.Token[token]; ok {
fmt.Printf("Url gefunden %s mit Hash: %v \n", s.Url[hash].URL, hash)
value = s.Url[hash].URL
fmt.Printf("Value: %V \n", value)
return true
}
return false
}