upgrade kratos

pull/498/head
小旭 5 years ago
parent 094ee714bd
commit 21b7b19008
  1. 2
      go.mod
  2. 12
      go.sum
  3. 10
      tool/kratos-gen-project/main.go
  4. 2
      tool/kratos-gen-project/new.go
  5. 4
      tool/kratos/build.go
  6. 78
      tool/kratos/env.go
  7. 6
      tool/kratos/main.go
  8. 4
      tool/kratos/run.go
  9. 592
      tool/kratos/template.go
  10. 9
      tool/kratos/tool.go
  11. 4
      tool/kratos/version.go

@ -4,6 +4,7 @@ go 1.13
require (
github.com/BurntSushi/toml v0.3.1
github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d // indirect
github.com/aristanetworks/goarista v0.0.0-20190912214011-b54698eaaca6 // indirect
github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f // indirect
github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f // indirect
@ -46,6 +47,7 @@ require (
github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5 // indirect
github.com/tsuna/gohbase v0.0.0-20190502052937-24ffed0537aa
github.com/urfave/cli v1.22.1
github.com/urfave/cli/v2 v2.1.1
go.etcd.io/etcd v0.0.0-20190917205325-a14579fbfb1a
go.uber.org/atomic v1.4.0 // indirect
go.uber.org/multierr v1.2.0 // indirect

@ -5,8 +5,8 @@ github.com/DataDog/zstd v1.3.6-0.20190409195224-796139022798/go.mod h1:1jcaCB/uf
github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo=
github.com/Shopify/sarama v1.23.1/go.mod h1:XLH1GYJnLVE0XCr6KdJGVJRTwY30moWNJ4sERjXX6fs=
github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI=
github.com/StackExchange/wmi v0.0.0-20180116203802-5d049714c4a6 h1:fLjPD/aNc3UIOA6tDi6QXUemppXK3P9BI7mr2hd6gx8=
github.com/StackExchange/wmi v0.0.0-20180116203802-5d049714c4a6/go.mod h1:3eOhrUMpNV+6aFIbp5/iudMxNCF27Vw2OZgy4xEx0Fg=
github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d h1:G0m3OIz70MZUWq3EgK3CesDbo8upS2Vm9/P3FtgI+Jk=
github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d/go.mod h1:3eOhrUMpNV+6aFIbp5/iudMxNCF27Vw2OZgy4xEx0Fg=
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
github.com/aristanetworks/fsnotify v1.4.2/go.mod h1:D/rtu7LpjYM8tRJphJ0hUBYpjai8SfX+aSNsWDTq/Ks=
@ -70,7 +70,6 @@ github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeME
github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
github.com/go-ole/go-ole v1.2.1/go.mod h1:7FAglXiTm7HKlQRDeOQ6ZNUHidzCWXuZWq/1dTyBNF8=
github.com/go-ole/go-ole v1.2.4 h1:nNBDSCOigTSiarFpYE9J/KtEA1IOW4CNeqT9TQDqCxI=
github.com/go-ole/go-ole v1.2.4/go.mod h1:XCwSNxSkXRo4vlyPy93sltvi/qJq0jqQhjqQNIwKuxM=
github.com/go-playground/locales v0.12.1 h1:2FITxuFt/xuCNP1Acdhv62OzaCiviiE4kotfhkmOqEc=
@ -243,9 +242,8 @@ github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQD
github.com/samuel/go-zookeeper v0.0.0-20180130194729-c4fab1ac1bec h1:6ncX5ko6B9LntYM0YBRXkiSaZMmLYeZ/NWcmeB43mMY=
github.com/samuel/go-zookeeper v0.0.0-20180130194729-c4fab1ac1bec/go.mod h1:gi+0XIa01GRL2eRQVjQkKGqKF3SF9vZR/HnPullcV2E=
github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0=
github.com/shirou/gopsutil v2.19.6+incompatible h1:49/Gru26Lne9Cl3IoAVDZVM09hvkSrUodgIIsCVRwbs=
github.com/shirou/gopsutil v2.19.6+incompatible/go.mod h1:WWnYX4lzhCH5h/3YBfyVA3VbLYjlMZZAQcW9ojMexNc=
github.com/shirou/w32 v0.0.0-20160930032740-bb4de0191aa4/go.mod h1:qsXQc7+bwAM3Q1u/4XEfrquwF8Lw7D7y5cD8CuHnfIc=
github.com/shirou/gopsutil v2.19.11+incompatible h1:lJHR0foqAjI4exXqWsU3DbH7bX1xvdhGdnXTIARA9W4=
github.com/shirou/gopsutil v2.19.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA=
github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/siddontang/go v0.0.0-20180604090527-bdc77568d726 h1:xT+JlYxNGqyT+XcU8iUrN18JYed2TvG9yN5ULG2jATM=
@ -289,6 +287,8 @@ github.com/urfave/cli v1.20.0 h1:fDqGv3UG/4jbVl/QkFwEdddtEDjh/5Ov6X+0B/3bPaw=
github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA=
github.com/urfave/cli v1.22.1 h1:+mkCCcOFKPnCmVYVcURKps1Xe+3zP90gSYGNfRkjoIY=
github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0=
github.com/urfave/cli/v2 v2.1.1 h1:Qt8FeAtxE/vfdrLmR3rxR6JRE0RoVmbXu8+6kZtYU4k=
github.com/urfave/cli/v2 v2.1.1/go.mod h1:SE9GqnLQmjVa0iPEY0f1w3ygNIYcIJ0OKPMoW2caLfQ=
github.com/xdg/scram v0.0.0-20180814205039-7eeb5667e42c/go.mod h1:lB8K/P019DLNhemzwFU4jHLhdvlE6uDZjXFejJXr49I=
github.com/xdg/stringprep v1.0.0/go.mod h1:Jhud4/sHMO4oL310DaZAKk9ZaJ08SJfe+sJh0HrGL1Y=
github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2 h1:eY9dn8+vbi4tKz5Qo6v2eYzo7kUS51QINcR5jNpbZS8=

@ -4,7 +4,7 @@ import (
"os"
"strings"
"github.com/urfave/cli"
"github.com/urfave/cli/v2"
)
var appHelpTemplate = `{{if .Usage}}{{.Usage}}{{end}}
@ -38,23 +38,23 @@ func main() {
app.HideVersion = true
app.CustomAppHelpTemplate = appHelpTemplate
app.Flags = []cli.Flag{
cli.StringFlag{
&cli.StringFlag{
Name: "d",
Value: "",
Usage: "指定项目所在目录",
Destination: &p.path,
},
cli.BoolFlag{
&cli.BoolFlag{
Name: "http",
Usage: "只使用http 不使用grpc",
Destination: &p.onlyHTTP,
},
cli.BoolFlag{
&cli.BoolFlag{
Name: "grpc",
Usage: "只使用grpc 不使用http",
Destination: &p.onlyGRPC,
},
cli.BoolFlag{
&cli.BoolFlag{
Name: "proto",
Usage: "废弃参数 无作用",
Destination: &p.none,

@ -9,7 +9,7 @@ import (
common "github.com/bilibili/kratos/tool/pkg"
"github.com/urfave/cli"
"github.com/urfave/cli/v2"
)
func runNew(ctx *cli.Context) (err error) {

@ -8,7 +8,7 @@ import (
"path"
"path/filepath"
"github.com/urfave/cli"
"github.com/urfave/cli/v2"
)
func buildAction(c *cli.Context) error {
@ -16,7 +16,7 @@ func buildAction(c *cli.Context) error {
if err != nil {
panic(err)
}
args := append([]string{"build"}, c.Args()...)
args := append([]string{"build"}, c.Args().Slice()...)
cmd := exec.Command("go", args...)
cmd.Dir = buildDir(base, "cmd", 5)
cmd.Stdout = os.Stdout

@ -0,0 +1,78 @@
package main
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sync"
)
var envCache struct {
once sync.Once
m map[string]string
}
// EnvFile returns the name of the Go environment configuration file.
func EnvFile() (string, error) {
if file := os.Getenv("GOENV"); file != "" {
if file == "off" {
return "", fmt.Errorf("GOENV=off")
}
return file, nil
}
dir, err := os.UserConfigDir()
if err != nil {
return "", err
}
if dir == "" {
return "", fmt.Errorf("missing user-config dir")
}
return filepath.Join(dir, "go/env"), nil
}
func initEnvCache() {
envCache.m = make(map[string]string)
file, _ := EnvFile()
if file == "" {
return
}
data, err := ioutil.ReadFile(file)
if err != nil {
return
}
for len(data) > 0 {
// Get next line.
line := data
i := bytes.IndexByte(data, '\n')
if i >= 0 {
line, data = line[:i], data[i+1:]
} else {
data = nil
}
i = bytes.IndexByte(line, '=')
if i < 0 || line[0] < 'A' || 'Z' < line[0] {
// Line is missing = (or empty) or a comment or not a valid env name. Ignore.
// (This should not happen, since the file should be maintained almost
// exclusively by "go env -w", but better to silently ignore than to make
// the go command unusable just because somehow the env file has
// gotten corrupted.)
continue
}
key, val := line[:i], line[i+1:]
envCache.m[string(key)] = string(val)
}
}
// Getenv gets the value from env or configuration.
func Getenv(key string) string {
val := os.Getenv(key)
if val != "" {
return val
}
envCache.once.Do(initEnvCache)
return envCache.m[key]
}

@ -4,7 +4,7 @@ import (
"fmt"
"os"
"github.com/urfave/cli"
"github.com/urfave/cli/v2"
)
func main() {
@ -12,7 +12,7 @@ func main() {
app.Name = "kratos"
app.Usage = "kratos工具集"
app.Version = Version
app.Commands = []cli.Command{
app.Commands = []*cli.Command{
{
Name: "new",
Aliases: []string{"n"},
@ -61,5 +61,5 @@ func main() {
}
func runNew(ctx *cli.Context) error {
return installAndRun("genproject", ctx.Args())
return installAndRun("genproject", ctx.Args().Slice())
}

@ -6,7 +6,7 @@ import (
"path"
"path/filepath"
"github.com/urfave/cli"
"github.com/urfave/cli/v2"
)
func runAction(c *cli.Context) error {
@ -16,7 +16,7 @@ func runAction(c *cli.Context) error {
}
dir := buildDir(base, "cmd", 5)
conf := path.Join(filepath.Dir(dir), "configs")
args := append([]string{"run", "main.go", "-conf", conf}, c.Args()...)
args := append([]string{"run", "main.go", "-conf", conf}, c.Args().Slice()...)
cmd := exec.Command("go", args...)
cmd.Dir = dir
cmd.Stdout = os.Stdout

@ -1,592 +0,0 @@
package main
const (
_tplAppToml = `
# This is a TOML document. Boom~
`
_tplMySQLToml = `
[demo]
addr = "127.0.0.1:3306"
dsn = "{user}:{password}@tcp(127.0.0.1:3306)/{database}?timeout=1s&readTimeout=1s&writeTimeout=1s&parseTime=true&loc=Local&charset=utf8mb4,utf8"
readDSN = ["{user}:{password}@tcp(127.0.0.2:3306)/{database}?timeout=1s&readTimeout=1s&writeTimeout=1s&parseTime=true&loc=Local&charset=utf8mb4,utf8","{user}:{password}@tcp(127.0.0.3:3306)/{database}?timeout=1s&readTimeout=1s&writeTimeout=1s&parseTime=true&loc=Local&charset=utf8,utf8mb4"]
active = 20
idle = 10
idleTimeout ="4h"
queryTimeout = "200ms"
execTimeout = "300ms"
tranTimeout = "400ms"
`
_tplMCToml = `
demoExpire = "24h"
[demo]
name = "{{.Name}}"
proto = "tcp"
addr = "127.0.0.1:11211"
active = 50
idle = 10
dialTimeout = "100ms"
readTimeout = "200ms"
writeTimeout = "300ms"
idleTimeout = "80s"
`
_tplRedisToml = `
demoExpire = "24h"
[demo]
name = "{{.Name}}"
proto = "tcp"
addr = "127.0.0.1:6389"
idle = 10
active = 10
dialTimeout = "1s"
readTimeout = "1s"
writeTimeout = "1s"
idleTimeout = "10s"
`
_tplHTTPToml = `
[server]
addr = "0.0.0.0:8000"
timeout = "1s"
`
_tplGRPCToml = `
[server]
addr = "0.0.0.0:9000"
timeout = "1s"
`
_tplChangeLog = `## {{.Name}}
### v1.0.0
1. 上线功能xxx
`
_tplMain = `package main
import (
"context"
"flag"
"os"
"os/signal"
"syscall"
"time"
"{{.ModuleName}}/internal/server/http"
"{{.ModuleName}}/internal/service"
"github.com/bilibili/kratos/pkg/conf/paladin"
"github.com/bilibili/kratos/pkg/log"
_ "go.uber.org/automaxprocs"
)
func main() {
flag.Parse()
if err := paladin.Init(); err != nil {
panic(err)
}
log.Init(nil) // debug flag: log.dir={path}
defer log.Close()
log.Info("{{.Name}} start")
svc := service.New()
httpSrv := http.New(svc)
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)
for {
s := <-c
log.Info("get a signal %s", s.String())
switch s {
case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:
ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second)
if err := httpSrv.Shutdown(ctx); err != nil {
log.Error("httpSrv.Shutdown error(%v)", err)
}
log.Info("{{.Name}} exit")
svc.Close()
cancel()
time.Sleep(time.Second)
return
case syscall.SIGHUP:
default:
return
}
}
}
`
_tplGRPCMain = `package main
import (
"context"
"flag"
"os"
"os/signal"
"syscall"
"time"
"{{.ModuleName}}/internal/server/grpc"
"{{.ModuleName}}/internal/server/http"
"{{.ModuleName}}/internal/service"
"github.com/bilibili/kratos/pkg/conf/paladin"
"github.com/bilibili/kratos/pkg/log"
_ "go.uber.org/automaxprocs"
)
func main() {
flag.Parse()
if err := paladin.Init(); err != nil {
panic(err)
}
log.Init(nil) // debug flag: log.dir={path}
defer log.Close()
log.Info("{{.Name}} start")
svc := service.New()
grpcSrv := grpc.New(svc)
httpSrv := http.New(svc)
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)
for s := range c {
log.Info("get a signal %s", s.String())
switch s {
case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:
ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second)
if err := grpcSrv.Shutdown(ctx); err != nil {
log.Error("grpcSrv.Shutdown error(%v)", err)
}
if err := httpSrv.Shutdown(ctx); err != nil {
log.Error("httpSrv.Shutdown error(%v)", err)
}
log.Info("{{.Name}} exit")
svc.Close()
cancel()
time.Sleep(time.Second)
return
case syscall.SIGHUP:
default:
return
}
}
}
`
_tplContributors = `# Owner
{{.Owner}}
# Author
# Reviewer
`
_tplDao = `package dao
import (
"context"
"time"
"github.com/bilibili/kratos/pkg/cache/memcache"
"github.com/bilibili/kratos/pkg/cache/redis"
"github.com/bilibili/kratos/pkg/conf/paladin"
"github.com/bilibili/kratos/pkg/database/sql"
"github.com/bilibili/kratos/pkg/log"
xtime "github.com/bilibili/kratos/pkg/time"
)
// Dao dao interface
type Dao interface {
Close()
Ping(ctx context.Context) (err error)
}
// dao dao.
type dao struct {
db *sql.DB
redis *redis.Pool
redisExpire int32
mc *memcache.Memcache
mcExpire int32
}
func checkErr(err error) {
if err != nil {
panic(err)
}
}
// New new a dao and return.
func New() (Dao) {
var (
dc struct {
Demo *sql.Config
}
rc struct {
Demo *redis.Config
DemoExpire xtime.Duration
}
mc struct {
Demo *memcache.Config
DemoExpire xtime.Duration
}
)
checkErr(paladin.Get("mysql.toml").UnmarshalTOML(&dc))
checkErr(paladin.Get("redis.toml").UnmarshalTOML(&rc))
checkErr(paladin.Get("memcache.toml").UnmarshalTOML(&mc))
return &dao{
// mysql
db: sql.NewMySQL(dc.Demo),
// redis
redis: redis.NewPool(rc.Demo),
redisExpire: int32(time.Duration(rc.DemoExpire) / time.Second),
// memcache
mc: memcache.New(mc.Demo),
mcExpire: int32(time.Duration(mc.DemoExpire) / time.Second),
}
}
// Close close the resource.
func (d *dao) Close() {
d.mc.Close()
d.redis.Close()
d.db.Close()
}
// Ping ping the resource.
func (d *dao) Ping(ctx context.Context) (err error) {
if err = d.pingMC(ctx); err != nil {
return
}
if err = d.pingRedis(ctx); err != nil {
return
}
return d.db.Ping(ctx)
}
func (d *dao) pingMC(ctx context.Context) (err error) {
if err = d.mc.Set(ctx, &memcache.Item{Key: "ping", Value: []byte("pong"), Expiration: 0}); err != nil {
log.Error("conn.Set(PING) error(%v)", err)
}
return
}
func (d *dao) pingRedis(ctx context.Context) (err error) {
conn := d.redis.Get(ctx)
defer conn.Close()
if _, err = conn.Do("SET", "ping", "pong"); err != nil {
log.Error("conn.Set(PING) error(%v)", err)
}
return
}
`
_tplReadme = `# {{.Name}}
## 项目简介
1.
`
_tplService = `package service
import (
"context"
"{{.ModuleName}}/internal/dao"
"github.com/bilibili/kratos/pkg/conf/paladin"
)
// Service service.
type Service struct {
ac *paladin.Map
dao dao.Dao
}
// New new a service and return.
func New() (s *Service) {
var ac = new(paladin.TOML)
if err := paladin.Watch("application.toml", ac); err != nil {
panic(err)
}
s = &Service{
ac: ac,
dao: dao.New(),
}
return s
}
// Ping ping the resource.
func (s *Service) Ping(ctx context.Context) (err error) {
return s.dao.Ping(ctx)
}
// Close close the resource.
func (s *Service) Close() {
s.dao.Close()
}
`
_tplGPRCService = `package service
import (
"context"
"fmt"
pb "{{.ModuleName}}/api"
"{{.ModuleName}}/internal/dao"
"github.com/bilibili/kratos/pkg/conf/paladin"
"github.com/golang/protobuf/ptypes/empty"
)
// Service service.
type Service struct {
ac *paladin.Map
dao dao.Dao
}
// New new a service and return.
func New() (s *Service) {
var ac = new(paladin.TOML)
if err := paladin.Watch("application.toml", ac); err != nil {
panic(err)
}
s = &Service{
ac: ac,
dao: dao.New(),
}
return s
}
// SayHello grpc demo func.
func (s *Service) SayHello(ctx context.Context, req *pb.HelloReq) (reply *empty.Empty, err error) {
reply = new(empty.Empty)
fmt.Printf("hello %s", req.Name)
return
}
// SayHelloURL bm demo func.
func (s *Service) SayHelloURL(ctx context.Context, req *pb.HelloReq) (reply *pb.HelloResp, err error) {
reply = &pb.HelloResp{
Content: "hello " + req.Name,
}
fmt.Printf("hello url %s", req.Name)
return
}
// Ping ping the resource.
func (s *Service) Ping(ctx context.Context) (err error) {
return s.dao.Ping(ctx)
}
// Close close the resource.
func (s *Service) Close() {
s.dao.Close()
}
`
_tplHTTPServer = `package http
import (
"net/http"
"{{.ModuleName}}/internal/model"
"{{.ModuleName}}/internal/service"
"github.com/bilibili/kratos/pkg/conf/paladin"
"github.com/bilibili/kratos/pkg/log"
bm "github.com/bilibili/kratos/pkg/net/http/blademaster"
)
var (
svc *service.Service
)
// New new a bm server.
func New(s *service.Service) (engine *bm.Engine) {
var (
hc struct {
Server *bm.ServerConfig
}
)
if err := paladin.Get("http.toml").UnmarshalTOML(&hc); err != nil {
if err != paladin.ErrNotExist {
panic(err)
}
}
svc = s
engine = bm.DefaultServer(hc.Server)
initRouter(engine)
if err := engine.Start(); err != nil {
panic(err)
}
return
}
func initRouter(e *bm.Engine) {
e.Ping(ping)
g := e.Group("/{{.Name}}")
{
g.GET("/start", howToStart)
}
}
func ping(ctx *bm.Context) {
if err := svc.Ping(ctx); err != nil {
log.Error("ping error(%v)", err)
ctx.AbortWithStatus(http.StatusServiceUnavailable)
}
}
// example for http request handler.
func howToStart(c *bm.Context) {
k := &model.Kratos{
Hello: "Golang 大法好 !!!",
}
c.JSON(k, nil)
}
`
_tplPBHTTPServer = `package http
import (
"net/http"
pb "{{.ModuleName}}/api"
"{{.ModuleName}}/internal/model"
"{{.ModuleName}}/internal/service"
"github.com/bilibili/kratos/pkg/conf/paladin"
"github.com/bilibili/kratos/pkg/log"
bm "github.com/bilibili/kratos/pkg/net/http/blademaster"
)
var (
svc *service.Service
)
// New new a bm server.
func New(s *service.Service) (engine *bm.Engine) {
var (
hc struct {
Server *bm.ServerConfig
}
)
if err := paladin.Get("http.toml").UnmarshalTOML(&hc); err != nil {
if err != paladin.ErrNotExist {
panic(err)
}
}
svc = s
engine = bm.DefaultServer(hc.Server)
pb.RegisterDemoBMServer(engine, svc)
initRouter(engine)
if err := engine.Start(); err != nil {
panic(err)
}
return
}
func initRouter(e *bm.Engine) {
e.Ping(ping)
g := e.Group("/{{.Name}}")
{
g.GET("/start", howToStart)
}
}
func ping(ctx *bm.Context) {
if err := svc.Ping(ctx); err != nil {
log.Error("ping error(%v)", err)
ctx.AbortWithStatus(http.StatusServiceUnavailable)
}
}
// example for http request handler.
func howToStart(c *bm.Context) {
k := &model.Kratos{
Hello: "Golang 大法好 !!!",
}
c.JSON(k, nil)
}
`
_tplAPIProto = `// 定义项目 API 的 proto 文件 可以同时描述 gRPC 和 HTTP API
// protobuf 文件参考:
// - https://developers.google.com/protocol-buffers/
syntax = "proto3";
import "github.com/gogo/protobuf/gogoproto/gogo.proto";
import "google/protobuf/empty.proto";
import "google/api/annotations.proto";
// package 命名使用 {appid}.{version} 的方式, version 形如 v1, v2 ..
package demo.service.v1;
// NOTE: 最后请删除这些无用的注释 (゜-゜)つロ
option go_package = "api";
option (gogoproto.goproto_getters_all) = false;
service Demo {
rpc SayHello (HelloReq) returns (.google.protobuf.Empty);
rpc SayHelloURL(HelloReq) returns (HelloResp) {
option (google.api.http) = {
get:"/{{.Name}}/say_hello"
};
};
}
message HelloReq {
string name = 1 [(gogoproto.moretags)='form:"name" validate:"required"'];
}
message HelloResp {
string Content = 1 [(gogoproto.jsontag) = 'content'];
}
`
_tplModel = `package model
// Kratos hello kratos.
type Kratos struct {
Hello string
}`
_tplGoMod = `module {{.ModuleName}}
go 1.12
require (
github.com/bilibili/kratos master
github.com/gogo/protobuf v1.2.1
github.com/golang/protobuf v1.3.2
golang.org/x/net v0.0.0-20190628185345-da137c7871d7
google.golang.org/grpc v1.22.0
)
`
_tplGRPCServer = `package grpc
import (
pb "{{.ModuleName}}/api"
"{{.ModuleName}}/internal/service"
"github.com/bilibili/kratos/pkg/conf/paladin"
"github.com/bilibili/kratos/pkg/net/rpc/warden"
)
// New new a grpc server.
func New(svc *service.Service) *warden.Server {
var rc struct {
Server *warden.ServerConfig
}
if err := paladin.Get("grpc.toml").UnmarshalTOML(&rc); err != nil {
if err != paladin.ErrNotExist {
panic(err)
}
}
ws := warden.NewServer(rc.Server)
pb.RegisterDemoServer(ws.Server(), svc)
ws, err := ws.Start()
if err != nil {
panic(err)
}
return ws
}
`
_tplGogen = `package api
//go:generate kratos tool protoc --swagger --grpc --bm api.proto
`
)

@ -13,7 +13,7 @@ import (
"time"
"github.com/fatih/color"
"github.com/urfave/cli"
"github.com/urfave/cli/v2"
)
const (
@ -71,7 +71,7 @@ func toolAction(c *cli.Context) (err error) {
}
return
}
if e := installAndRun(commond, c.Args()[1:]); e != nil {
if e := installAndRun(commond, c.Args().Slice()[1:]); e != nil {
fmt.Fprintf(os.Stderr, fmt.Sprintf("%v\n", e))
}
return
@ -179,7 +179,8 @@ func (t Tool) toolPath() string {
if name == "" {
name = t.Name
}
if gobin := os.Getenv("GOBIN"); len(gobin) > 0 {
gobin := Getenv("GOBIN")
if gobin != "" {
return filepath.Join(gobin, name)
}
return filepath.Join(gopath(), "bin", name)
@ -226,7 +227,7 @@ func (t Tool) updated() bool {
}
func gopath() (gp string) {
gopaths := strings.Split(os.Getenv("GOPATH"), string(filepath.ListSeparator))
gopaths := strings.Split(Getenv("GOPATH"), string(filepath.ListSeparator))
if len(gopaths) == 1 && gopaths[0] != "" {
return gopaths[0]

@ -8,9 +8,9 @@ import (
var (
// Version is version
Version = "0.3.2"
Version = "0.3.3"
// BuildTime is BuildTime
BuildTime = "2019/12/19"
BuildTime = "2020/1/19"
)
// VersionOptions include version

Loading…
Cancel
Save