在自定义范围内生成随机数

I have go script that starts on "localhost:8080/1" with a previous and next links I need to add Random link with custom range that I can change like:

  • small numbers like 100 to 200 "localhost:8080/100 - 200" and
  • even to big number like: "16567684686592643791596485465456223131545455682945955"

So:

// Get next and previous page numbers

previous := new(big.Int).Sub(page, one)
next := new(big.Int).Add(page, one)
random :=????

You need to use the package crypto.rand Int() function, which does support big.Int (as opposed to the math.rand package)

See this article (and its playground example):

package main

import (
    "fmt"
    "math/big"
    "crypto/rand"
)

func main() {
    var prime1, _ = new(big.Int).SetString("21888242871839275222246405745257275088548364400416034343698204186575808495617", 10)
    // Generate random numbers in range [0..prime1]
    // Ignore error values
    // Don't use this code to generate secret keys that protect important stuff!
    x, _ := rand.Int(rand.Reader, prime1)
    y, _ := rand.Int(rand.Reader, prime1)
    fmt.Printf("x: %v
", x)
    fmt.Printf("y: %v
", y)

}