普通网友 2017-10-19 15:00 采纳率: 0%
浏览 228
已采纳

为什么我的随机数不更新?

I am doing the following in Golang (hosted on Appengine)

Whenever I initiate the app by running dev_appserver command and I access the page at localhost:8080, I get a page with a new random number between 1 and 19. But on refreshing the page in the browser, this number does not change. If I kill the server and re-initiate by running dev_appserver, I get a new random number. How do I get the random number to update on page refresh.

Code follows:

package testpage

import (
    "fmt"
    "net/http"
    "math/rand"
    "time"
    "strconv"
)

func init() {
    http.HandleFunc("/", handler)
}

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, varHtml)
}
func random(min, max int) int {
    rand.Seed(time.Now().Unix())
    return rand.Intn(max - min) + min
}

var myrand = strconv.Itoa(random(1, 19))
var varHtml = `

Random number is ` + myrand 
  • 写回答

1条回答 默认 最新

  • dongye3917 2017-10-19 15:13
    关注

    The varHtml is a package level variable and is calculated just once.

    You should move it to the handler as:

    func handler(w http.ResponseWriter, r *http.Request) {
        var varHtml = `Random number is ` + strconv.Itoa(random(1, 19))
        fmt.Fprint(w, varHtml)
    }
    

    Also there is no need to seed rand every time.

    It's better to do it at package init():

    func init() {
        rand.Seed(time.Now().Unix())
    }
    
    func random(min, max int) int {
        return rand.Intn(max - min) + min
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路