dtnd30892
dtnd30892
2016-07-06 14:23

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 douge3492 5年前

    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
    }
    
    点赞 评论 复制链接分享
  • duan0424 duan0424 5年前

    If you are only worried about the output in that manner, then following will work:

    func RepoCreateActivity(t Activity) string {
    activities = append(activities, t)
    b := ActivityReturn{Cgid: RandomString(10)}
    temp,_:=json.Marshal(b)
    return string(temp)
    }
    

    Note that output in this case is string.

    点赞 评论 复制链接分享

相关推荐