dtnd30892 2016-07-06 14:23
浏览 20
已采纳

Golang,添加项目并返回带有随机字符串的新结构

I am trying to figure out how to set up a basic endpoint in golang. I have a call that takes a payload and adds it to a list (in memory right now). Previously it was just returning the exact payload it was getting. I would like it to return a new json object with a randomly generated string. Here it what it looked like initially :

in my repo.go

func RepoCreateActivity(t Activity) Activity {
    activities = append(activities, t)
    return t
} 

and this works fine. However I would like to return a different object with randomly generated string, here is what I have tried

in my repo.go (the randomstring function is from a bit of googling - https://siongui.github.io/2015/04/13/go-generate-random-string/ )

 func RandomString(strlen int) string {
    rand.Seed(time.Now().UTC().UnixNano())
    const chars = "abcdefghijklmnopqrstuvwxyz0123456789"
    result := make([]byte, strlen)
    for i := 0; i < strlen; i++ {
        result[i] = chars[rand.Intn(len(chars))]
    }
    return string(result)
}

func RepoCreateActivity(t Activity) ActivityReturn {
    activities = append(activities, t)
    b := ActivityReturn({Cgid: RandomString(10)})
    return b
}

The actvitityReturn.go looks like :

package main

type ActivityReturn struct {
    Cgid   string   `json:"cgid"`
}

I cannot seem to get this right. I just want the call to return a { cgid : "random string here" }. I am still working through learning golang and any advice would be greatly appreciated. Thanks!

  • 写回答

2条回答 默认 最新

  • douge3492 2016-07-06 14:37
    关注

    I think you might be creating your struct incorrectly. Could you perhaps give this a try?

    func RepoCreateActivity(t Activity) ActivityReturn {
        activities = append(activities, t)
        b := ActivityReturn{Cgid: RandomString(10)} // remove parens
        return b
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 全志H618ROM新增分区
  • ¥20 jupyter保存图像功能的实现
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示
  • ¥15 NAO机器人的录音程序保存问题
  • ¥15 C#读写EXCEL文件,不同编译
  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况