feat: add joke api (#294)

* feat: add joke api
close #124

* chore: count boundary

* fix: bug fix
chore: update README.md

* feat: add publicapi.json
This commit is contained in:
zhaoyang
2021-12-08 18:38:03 +08:00
committed by GitHub
parent 1688a9efdd
commit 72827704d2
15 changed files with 787 additions and 0 deletions

43
joke/handler/joke.go Normal file
View File

@@ -0,0 +1,43 @@
package handler
import (
"context"
"math/rand"
"github.com/micro/services/joke/model"
pb "github.com/micro/services/joke/proto"
)
type Joke struct{}
// Random is used to get random jokes
func (e *Joke) Random(_ context.Context, req *pb.RandomRequest, rsp *pb.RandomResponse) error {
jokes := model.GetAllJokes()
count := req.Count
if count <= 0 {
count = 1
} else if count > 10 {
count = 10
}
if count > int32(len(jokes)) {
count = int32(len(jokes))
}
for i := int32(0); i < count; i++ {
random := jokes[rand.Intn(len(jokes))]
info := &pb.JokeInfo{
Id: random.Id,
Title: random.Title,
Body: random.Body,
Category: random.Category,
Source: random.Source,
}
rsp.Jokes = append(rsp.Jokes, info)
}
return nil
}