Skip to content

Commit

Permalink
fixbug:schema will not upload to service-center when first register (#…
Browse files Browse the repository at this point in the history
…623)

* fixbug:schema will not upload to service-center when first register

* Doc update,add:
1、Define the contents of the schema file in URLPatterns()
2、Automatically generate schema file in local directory

* fixbug:schema will not upload to service-center when first register
Doc update,add:
1、Define the contents of the schema file in URLPatterns()
2、Automatically generate schema file in local directory
  • Loading branch information
wangqj authored and tianxiaoliang committed May 20, 2019
1 parent 5c2eef9 commit 273aa99
Show file tree
Hide file tree
Showing 8 changed files with 245 additions and 31 deletions.
18 changes: 18 additions & 0 deletions core/config/schema/loader.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import (
"errors"
"fmt"
"github.com/go-chassis/go-chassis/core/common"
"github.com/go-chassis/go-chassis/pkg/runtime"
"github.com/go-chassis/go-chassis/pkg/util/fileutil"
swagger "github.com/go-chassis/go-restful-swagger20"
"github.com/go-mesh/openlogging"
"io/ioutil"
"os"
Expand Down Expand Up @@ -218,3 +220,19 @@ func init() {
defaultMicroserviceMetaMgr = make(map[string]*MicroserviceMeta)
DefaultSchemaIDsMap = make(map[string]string)
}

// SetSchemaInfo is for fill defaultMicroserviceMetaMgr and DefaultSchemaIDsMap
func SetSchemaInfo(sws *swagger.SwaggerService) error {
schemaInfoList, err := sws.GetSchemaInfoList()
if err != nil {
openlogging.Error("get schema Info err: " + err.Error())
return err
}
microsvcMeta := NewMicroserviceMeta(fileutil.SchemaDirectory)
microsvcMeta.SchemaIDs = append(microsvcMeta.SchemaIDs, runtime.ServiceName)
defaultMicroserviceMetaMgr[runtime.ServiceName] = microsvcMeta
for _, schemaInfo := range schemaInfoList {
DefaultSchemaIDsMap[runtime.ServiceName] = schemaInfo
}
return nil
}
22 changes: 22 additions & 0 deletions core/config/schema/loader_test.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package schema_test

import (
"github.com/emicklei/go-restful"
"github.com/go-chassis/go-chassis/core/config/schema"
"github.com/go-chassis/go-chassis/pkg/util/fileutil"
swagger "github.com/go-chassis/go-restful-swagger20"
"github.com/stretchr/testify/assert"
"log"
"os"
"path/filepath"
"sort"
Expand Down Expand Up @@ -118,3 +121,22 @@ func TestLoadSchema(t *testing.T) {
err = os.RemoveAll(fileutil.GetConfDir())
assert.Nil(t, err)
}

func TestSetSchemaIDs(t *testing.T) {
p := os.Getenv("GOPATH")
os.Setenv("CHASSIS_HOME", filepath.Join(p, "src", "github.com", "go-chassis", "go-chassis", "examples", "discovery", "server"))
log.Println(os.Getenv("CHASSIS_HOME"))
config := swagger.Config{
WebServices: restful.DefaultContainer.RegisteredWebServices(),
OpenService: true,
SwaggerPath: "/apidocs/",
SwaggerFilePath: filepath.Join(os.Getenv("CHASSIS_HOME"), "api.yaml")}
config.Info.Description = "This is a sample server Book server"
config.Info.Title = "swagger Book"
sws := swagger.RegisterSwaggerService(config, restful.DefaultContainer)
err := schema.SetSchemaInfo(sws)
assert.NoError(t, err)
s, e := schema.GetSchemaIDs("aaa")
assert.Error(t, e)
assert.Equal(t, 0, len(s))
}
31 changes: 27 additions & 4 deletions core/lager/logrotate_test.go
Original file line number Diff line number Diff line change
@@ -1,18 +1,41 @@
package lager_test
package lager

import (
"github.com/go-chassis/go-chassis/core/lager"
"github.com/stretchr/testify/assert"
"io/ioutil"
"testing"

"github.com/stretchr/testify/assert"
)

func TestCopyFile(t *testing.T) {
err := ioutil.WriteFile("./test.copy", []byte("test"), 0600)
assert.NoError(t, err)
err = lager.CopyFile("./test.copy", "./test2.copy")
err = CopyFile("./test.copy", "./test2.copy")
assert.NoError(t, err)
b, err := ioutil.ReadFile("./test2.copy")
assert.NoError(t, err)
assert.Equal(t, []byte("test"), b)
}

func Test_removeFile(t *testing.T) {
ioutil.WriteFile("./remove.copy", []byte("test"), 0600)
p := "remove.copy"

type args struct {
path string
}
tests := []struct {
name string
args args
wantErr bool
}{
{"remove", args{p}, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := removeFile(tt.args.path); (err != nil) != tt.wantErr {
t.Errorf("removeFile() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
5 changes: 3 additions & 2 deletions core/registry/bootstrap.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,9 @@ func RegisterMicroservice() error {

// RegisterMicroserviceInstances register micro-service instances
func RegisterMicroserviceInstances() error {
var err error
service := config.MicroserviceDefinition
runtime.Schemas, err = schema.GetSchemaIDs(service.ServiceDescription.Name)
for _, schemaID := range runtime.Schemas {
schemaInfo := schema.DefaultSchemaIDsMap[schemaID]
err := DefaultRegistrator.AddSchemas(runtime.ServiceID, schemaID, schemaInfo)
Expand All @@ -117,8 +120,6 @@ func RegisterMicroserviceInstances() error {
}

openlogging.Info("Start to register instance.")
service := config.MicroserviceDefinition
var err error

sid, err := DefaultServiceDiscoveryService.GetMicroServiceID(runtime.App, service.ServiceDescription.Name, service.ServiceDescription.Version, service.ServiceDescription.Environment)
if err != nil {
Expand Down
109 changes: 109 additions & 0 deletions docs/getstarted/writing-rest.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,5 +118,114 @@ func main() {
lager.Logger.Info(string(resp.ReadBody()))
}
```


### Define the contents of the schema file in URLPatterns()

Here you can configure Method、Path、Parameters,and so on.
For example:

```go
func (d *Data) URLPatterns() []rf.Route {
return []rf.Route{
{
Method:http.MethodGet,
Path:"/price/{id}",
ResourceFuncName:"GetPrice", #schema=operationId
Consumes: []string{goRestful.MIME_JSON,goRestful.MIME_XML},
Produces: []string{goRestful.MIME_JSON},
Returns: []*rf.Returns{{Code: http.StatusOK,Message:"true",Model: Data{}}},
Parameters:[]*rf.Parameters{#schema=parameter
&rf.Parameters{"x-auth-token","string",goRestful.HeaderParameterKind,"this is a token"},
&rf.Parameters{"x-auth-token2","string",goRestful.HeaderParameterKind,"this is a token"},
},
},
}
}
````
```yaml
swagger: "2.0"
info:
title: ""
version: ""
basePath: /
paths:
/price/{id}:
get:
operationId: GetPrice
parameters:
- name: x-auth-token
in: header
description: this is a token
type: string
- name: x-auth-token2
in: header
description: this is a token
type: string
consumes:
- application/json
- application/xml
produces:
- application/json
responses:
"200":
description: "true"
schema:
$ref: '#/definitions/Data'
definitions:
Data:
type: object
properties:
err:
$ref: '#/definitions/ErrorCode'
priceID:
type: string
type:
type: string
value:
type: string
ErrorCode:
type: object
properties:
code:
type: integer
format: ""
```

Paramater type

```go
// PathParameterKind = indicator of Request parameter type "path"
PathParameterKind = iota
// QueryParameterKind = indicator of Request parameter type "query"
QueryParameterKind
// BodyParameterKind = indicator of Request parameter type "body"
BodyParameterKind
// HeaderParameterKind = indicator of Request parameter type "header"
HeaderParameterKind
// FormParameterKind = indicator of Request parameter type "form"
FormParameterKind
```

### Automatically generate schema file in local directory
The program will generate the schema file locally by default,If you want to define your own instead of automatically generating a schema,
You can modify the configuration '**noRefreshSchema: true**' in chassis.yaml

```yaml
cse:
service:
registry:
address: http://127.0.0.1:30100
protocols:
rest:
listenAddress: "127.0.0.1:5003"
noRefreshSchema: true
```


**Notice**
>> if conf folder is not under work dir, plz export CHASSIS_HOME=/path/to/conf/parent_folder or CHASSIS_CONF_DIR==/path/to/conf_folder
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ require (
github.com/go-chassis/foundation v0.0.0-20190516083152-b8b2476b6db7
github.com/go-chassis/go-archaius v0.16.0
github.com/go-chassis/go-chassis-config v0.7.0
github.com/go-chassis/go-restful-swagger20 v0.0.0-20181221101811-a33c76fe4a6e
github.com/go-chassis/go-restful-swagger20 v1.0.1
github.com/go-chassis/paas-lager v1.0.2-0.20190328010332-cf506050ddb2
github.com/go-logfmt/logfmt v0.4.0 // indirect
github.com/go-mesh/openlogging v0.0.0-20181205082104-3d418c478b2d
Expand Down
13 changes: 9 additions & 4 deletions server/restful/restful_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ func (r *restfulServer) register2GoRestful(routeSpec Route, handler restful.Rout
return nil
}

//handle parameter
//fillParam is for handle parameter by type
func fillParam(routeSpec Route, rb *restful.RouteBuilder) *restful.RouteBuilder {
for _, param := range routeSpec.Parameters {
switch param.ParamType {
Expand Down Expand Up @@ -243,7 +243,7 @@ func (r *restfulServer) Start() error {
r.server = &http.Server{Addr: config.Address, Handler: r.container}
}
// create schema
err = r.CreateSchema(config)
err = r.CreateLocalSchema(config)
if err != nil {
return err
}
Expand All @@ -269,7 +269,7 @@ func (r *restfulServer) Start() error {
}

//register to swagger ui,Whether to create a schema, you need to refer to the configuration.
func (r *restfulServer) CreateSchema(config server.Options) error {
func (r *restfulServer) CreateLocalSchema(config server.Options) error {
if globalconfig.GlobalDefinition.Cse.NoRefreshSchema == true {
openlogging.Info("will not create schema file. if you want to change it, please update chassis.yaml->NoRefreshSchema=true")
return nil
Expand All @@ -293,8 +293,13 @@ func (r *restfulServer) CreateSchema(config server.Options) error {
ApiPath: "/apidocs.json",
FileStyle: "yaml",
SwaggerFilePath: filepath.Join(path, runtime.ServiceName+".yaml")}
swagger.RegisterSwaggerService(swaggerConfig, r.container)
sws := swagger.RegisterSwaggerService(swaggerConfig, r.container)
openlogging.Info("The schema has been created successfully. path:" + path)
//set schema information when create local schema file
err := schema.SetSchemaInfo(sws)
if err != nil {
return fmt.Errorf("set schema information,%s", err.Error())
}
return nil
}

Expand Down
Loading

0 comments on commit 273aa99

Please sign in to comment.