mercredi 29 juillet 2020

How to create mirror URLs or unique identifiers linking to the URL within Go?

I'm a beginning Go programmer who is writing a web application---any help appreciated.

There are URLs for the webpages which are in the following format:

www.websitename.com/ucihvpl9yyl764p0g8szt9tutifxrf

My goal is to create a unique identifier on the webpage (of length N), which both links to this HTML, and creates a special URL of the format www.websitename.com/unique_identifer for users to easier access this HTML. This unique identifier should be created once, and not change.

It's clear to me how to generate a random string (see below), but it's not clear how to connect this to the HTML, or create a novel URL based on this unique token linking to the original URL.

I think I know how to generate a unique identifier with the following, using this link: https://blog.questionable.services/article/generating-secure-random-numbers-crypto-rand/

Here, the string is length 20

package main

import(
    "fmt"
    "crypto/rand"
    "encoding/base64"
)


// GenerateRandomBytes returns securely generated random bytes. 
func GenerateRandomBytes(n int) ([]byte, error) {
    b := make([]byte, n)
    _, err := rand.Read(b)
    // Note that err == nil only if we read len(b) bytes.
    if err != nil {
        return nil, err
    }

    return b, nil
}

// GenerateRandomString returns a URL-safe, base64 encoded securely generated random string.
func GenerateRandomString(s int) (string, error) {
    b, err := GenerateRandomBytes(s)
    return base64.URLEncoding.EncodeToString(b), err
}


func main() {
    token, err := GenerateRandomString(20)
    if err != nil {
        // Serve an appropriately vague error to the
        // user, but log the details internally.
    }
    fmt.Println(token)
}



Aucun commentaire:

Enregistrer un commentaire