Browse Source

Update LICENSE

tags/v1.5.0
Unknown 5 years ago
parent
commit
865272a7f7
7 changed files with 590 additions and 355 deletions
  1. 191
    0
      LICENSE
  2. 2
    6
      README.md
  3. 299
    269
      apiapp.go
  4. 57
    57
      new.go
  5. 27
    14
      test.go
  6. 12
    6
      util.go
  7. 2
    3
      watch.go

+ 191
- 0
LICENSE View File

@@ -0,0 +1,191 @@
1
+Apache License
2
+Version 2.0, January 2004
3
+http://www.apache.org/licenses/
4
+
5
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+1. Definitions.
8
+
9
+"License" shall mean the terms and conditions for use, reproduction, and
10
+distribution as defined by Sections 1 through 9 of this document.
11
+
12
+"Licensor" shall mean the copyright owner or entity authorized by the copyright
13
+owner that is granting the License.
14
+
15
+"Legal Entity" shall mean the union of the acting entity and all other entities
16
+that control, are controlled by, or are under common control with that entity.
17
+For the purposes of this definition, "control" means (i) the power, direct or
18
+indirect, to cause the direction or management of such entity, whether by
19
+contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
20
+outstanding shares, or (iii) beneficial ownership of such entity.
21
+
22
+"You" (or "Your") shall mean an individual or Legal Entity exercising
23
+permissions granted by this License.
24
+
25
+"Source" form shall mean the preferred form for making modifications, including
26
+but not limited to software source code, documentation source, and configuration
27
+files.
28
+
29
+"Object" form shall mean any form resulting from mechanical transformation or
30
+translation of a Source form, including but not limited to compiled object code,
31
+generated documentation, and conversions to other media types.
32
+
33
+"Work" shall mean the work of authorship, whether in Source or Object form, made
34
+available under the License, as indicated by a copyright notice that is included
35
+in or attached to the work (an example is provided in the Appendix below).
36
+
37
+"Derivative Works" shall mean any work, whether in Source or Object form, that
38
+is based on (or derived from) the Work and for which the editorial revisions,
39
+annotations, elaborations, or other modifications represent, as a whole, an
40
+original work of authorship. For the purposes of this License, Derivative Works
41
+shall not include works that remain separable from, or merely link (or bind by
42
+name) to the interfaces of, the Work and Derivative Works thereof.
43
+
44
+"Contribution" shall mean any work of authorship, including the original version
45
+of the Work and any modifications or additions to that Work or Derivative Works
46
+thereof, that is intentionally submitted to Licensor for inclusion in the Work
47
+by the copyright owner or by an individual or Legal Entity authorized to submit
48
+on behalf of the copyright owner. For the purposes of this definition,
49
+"submitted" means any form of electronic, verbal, or written communication sent
50
+to the Licensor or its representatives, including but not limited to
51
+communication on electronic mailing lists, source code control systems, and
52
+issue tracking systems that are managed by, or on behalf of, the Licensor for
53
+the purpose of discussing and improving the Work, but excluding communication
54
+that is conspicuously marked or otherwise designated in writing by the copyright
55
+owner as "Not a Contribution."
56
+
57
+"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
58
+of whom a Contribution has been received by Licensor and subsequently
59
+incorporated within the Work.
60
+
61
+2. Grant of Copyright License.
62
+
63
+Subject to the terms and conditions of this License, each Contributor hereby
64
+grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
65
+irrevocable copyright license to reproduce, prepare Derivative Works of,
66
+publicly display, publicly perform, sublicense, and distribute the Work and such
67
+Derivative Works in Source or Object form.
68
+
69
+3. Grant of Patent License.
70
+
71
+Subject to the terms and conditions of this License, each Contributor hereby
72
+grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
73
+irrevocable (except as stated in this section) patent license to make, have
74
+made, use, offer to sell, sell, import, and otherwise transfer the Work, where
75
+such license applies only to those patent claims licensable by such Contributor
76
+that are necessarily infringed by their Contribution(s) alone or by combination
77
+of their Contribution(s) with the Work to which such Contribution(s) was
78
+submitted. If You institute patent litigation against any entity (including a
79
+cross-claim or counterclaim in a lawsuit) alleging that the Work or a
80
+Contribution incorporated within the Work constitutes direct or contributory
81
+patent infringement, then any patent licenses granted to You under this License
82
+for that Work shall terminate as of the date such litigation is filed.
83
+
84
+4. Redistribution.
85
+
86
+You may reproduce and distribute copies of the Work or Derivative Works thereof
87
+in any medium, with or without modifications, and in Source or Object form,
88
+provided that You meet the following conditions:
89
+
90
+You must give any other recipients of the Work or Derivative Works a copy of
91
+this License; and
92
+You must cause any modified files to carry prominent notices stating that You
93
+changed the files; and
94
+You must retain, in the Source form of any Derivative Works that You distribute,
95
+all copyright, patent, trademark, and attribution notices from the Source form
96
+of the Work, excluding those notices that do not pertain to any part of the
97
+Derivative Works; and
98
+If the Work includes a "NOTICE" text file as part of its distribution, then any
99
+Derivative Works that You distribute must include a readable copy of the
100
+attribution notices contained within such NOTICE file, excluding those notices
101
+that do not pertain to any part of the Derivative Works, in at least one of the
102
+following places: within a NOTICE text file distributed as part of the
103
+Derivative Works; within the Source form or documentation, if provided along
104
+with the Derivative Works; or, within a display generated by the Derivative
105
+Works, if and wherever such third-party notices normally appear. The contents of
106
+the NOTICE file are for informational purposes only and do not modify the
107
+License. You may add Your own attribution notices within Derivative Works that
108
+You distribute, alongside or as an addendum to the NOTICE text from the Work,
109
+provided that such additional attribution notices cannot be construed as
110
+modifying the License.
111
+You may add Your own copyright statement to Your modifications and may provide
112
+additional or different license terms and conditions for use, reproduction, or
113
+distribution of Your modifications, or for any such Derivative Works as a whole,
114
+provided Your use, reproduction, and distribution of the Work otherwise complies
115
+with the conditions stated in this License.
116
+
117
+5. Submission of Contributions.
118
+
119
+Unless You explicitly state otherwise, any Contribution intentionally submitted
120
+for inclusion in the Work by You to the Licensor shall be under the terms and
121
+conditions of this License, without any additional terms or conditions.
122
+Notwithstanding the above, nothing herein shall supersede or modify the terms of
123
+any separate license agreement you may have executed with Licensor regarding
124
+such Contributions.
125
+
126
+6. Trademarks.
127
+
128
+This License does not grant permission to use the trade names, trademarks,
129
+service marks, or product names of the Licensor, except as required for
130
+reasonable and customary use in describing the origin of the Work and
131
+reproducing the content of the NOTICE file.
132
+
133
+7. Disclaimer of Warranty.
134
+
135
+Unless required by applicable law or agreed to in writing, Licensor provides the
136
+Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
137
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
138
+including, without limitation, any warranties or conditions of TITLE,
139
+NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
140
+solely responsible for determining the appropriateness of using or
141
+redistributing the Work and assume any risks associated with Your exercise of
142
+permissions under this License.
143
+
144
+8. Limitation of Liability.
145
+
146
+In no event and under no legal theory, whether in tort (including negligence),
147
+contract, or otherwise, unless required by applicable law (such as deliberate
148
+and grossly negligent acts) or agreed to in writing, shall any Contributor be
149
+liable to You for damages, including any direct, indirect, special, incidental,
150
+or consequential damages of any character arising as a result of this License or
151
+out of the use or inability to use the Work (including but not limited to
152
+damages for loss of goodwill, work stoppage, computer failure or malfunction, or
153
+any and all other commercial damages or losses), even if such Contributor has
154
+been advised of the possibility of such damages.
155
+
156
+9. Accepting Warranty or Additional Liability.
157
+
158
+While redistributing the Work or Derivative Works thereof, You may choose to
159
+offer, and charge a fee for, acceptance of support, warranty, indemnity, or
160
+other liability obligations and/or rights consistent with this License. However,
161
+in accepting such obligations, You may act only on Your own behalf and on Your
162
+sole responsibility, not on behalf of any other Contributor, and only if You
163
+agree to indemnify, defend, and hold each Contributor harmless for any liability
164
+incurred by, or claims asserted against, such Contributor by reason of your
165
+accepting any such warranty or additional liability.
166
+
167
+END OF TERMS AND CONDITIONS
168
+
169
+APPENDIX: How to apply the Apache License to your work
170
+
171
+To apply the Apache License to your work, attach the following boilerplate
172
+notice, with the fields enclosed by brackets "[]" replaced with your own
173
+identifying information. (Don't include the brackets!) The text should be
174
+enclosed in the appropriate comment syntax for the file format. We also
175
+recommend that a file or class name and description of purpose be included on
176
+the same "printed page" as the copyright notice for easier identification within
177
+third-party archives.
178
+
179
+   Copyright [yyyy] [name of copyright owner]
180
+
181
+   Licensed under the Apache License, Version 2.0 (the "License");
182
+   you may not use this file except in compliance with the License.
183
+   You may obtain a copy of the License at
184
+
185
+     http://www.apache.org/licenses/LICENSE-2.0
186
+
187
+   Unless required by applicable law or agreed to in writing, software
188
+   distributed under the License is distributed on an "AS IS" BASIS,
189
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190
+   See the License for the specific language governing permissions and
191
+   limitations under the License.

+ 2
- 6
README.md View File

@@ -1,10 +1,6 @@
1 1
 bee
2 2
 ===
3 3
 
4
-[![Build Status](https://drone.io/github.com/astaxie/bee/status.png)](https://drone.io/github.com/astaxie/bee/latest)
4
+[![Build Status](https://drone.io/github.com/beego/bee/status.png)](https://drone.io/github.com/beego/bee/latest)
5 5
 
6
-Bee is a tool for managing beego framework.
7
-
8
-## License
9
-
10
-[Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.html).
6
+Bee is a tool for helping develop with beego app framework.

+ 299
- 269
apiapp.go View File

@@ -1,269 +1,299 @@
1
-// Copyright 2013 bee authors
2
-//
3
-// Licensed under the Apache License, Version 2.0 (the "License"): you may
4
-// not use this file except in compliance with the License. You may obtain
5
-// a copy of the License at
6
-//
7
-//     http://www.apache.org/licenses/LICENSE-2.0
8
-//
9
-// Unless required by applicable law or agreed to in writing, software
10
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12
-// License for the specific language governing permissions and limitations
13
-// under the License.
14
-
15
-package main
16
-
17
-import (
18
-	"fmt"
19
-	"os"
20
-	path "path/filepath"
21
-	"strings"
22
-)
23
-
24
-var cmdApiapp = &Command{
25
-	// CustomFlags: true,
26
-	UsageLine: "api [appname]",
27
-	Short:     "create an api application base on beego framework",
28
-	Long: `
29
-create an api application base on beego framework
30
-
31
-In the current path, will create a folder named [appname]
32
-
33
-In the appname folder has the follow struct:
34
-
35
-	├── conf
36
-	│   └── app.conf
37
-	├── controllers
38
-	│   └── default.go
39
-	├── main.go
40
-	└── models
41
-	    └── object.go             
42
-
43
-`,
44
-}
45
-
46
-var apiconf = `
47
-appname = {{.Appname}}
48
-httpport = 8080
49
-runmode = dev
50
-autorender = false
51
-copyrequestbody = true
52
-`
53
-var apiMaingo = `package main
54
-
55
-import (
56
-	"github.com/astaxie/beego"
57
-	"{{.Appname}}/controllers"
58
-)
59
-
60
-//		Objects
61
-
62
-//	URL					HTTP Verb				Functionality
63
-//	/object				POST					Creating Objects
64
-//	/object/<objectId>	GET						Retrieving Objects
65
-//	/object/<objectId>	PUT						Updating Objects
66
-//	/object				GET						Queries
67
-//	/object/<objectId>	DELETE					Deleting Objects
68
-
69
-func main() {
70
-	beego.RESTRouter("/object", &controllers.ObejctController{})
71
-	beego.Run()
72
-}
73
-`
74
-var apiModels = `package models
75
-
76
-import (
77
-	"errors"
78
-	"strconv"
79
-	"time"
80
-)
81
-
82
-var (
83
-	Objects map[string]*Object
84
-)
85
-
86
-type Object struct {
87
-	ObjectId   string
88
-	Score      int64
89
-	PlayerName string
90
-}
91
-
92
-func init() {
93
-	Objects = make(map[string]*Object)
94
-	Objects["hjkhsbnmn123"] = &Object{"hjkhsbnmn123", 100, "astaxie"}
95
-	Objects["mjjkxsxsaa23"] = &Object{"mjjkxsxsaa23", 101, "someone"}
96
-}
97
-
98
-func AddOne(object Object) (ObjectId string) {
99
-	object.ObjectId = "astaxie" + strconv.FormatInt(time.Now().UnixNano(), 10)
100
-	Objects[object.ObjectId] = &object
101
-	return object.ObjectId
102
-}
103
-
104
-func GetOne(ObjectId string) (object *Object, err error) {
105
-	if v, ok := Objects[ObjectId]; ok {
106
-		return v, nil
107
-	}
108
-	return nil, errors.New("ObjectId Not Exist")
109
-}
110
-
111
-func GetAll() map[string]*Object {
112
-	return Objects
113
-}
114
-
115
-func Update(ObjectId string, Score int64) (err error) {
116
-	if v, ok := Objects[ObjectId]; ok {
117
-		v.Score = Score
118
-		return nil
119
-	}
120
-	return errors.New("ObjectId Not Exist")
121
-}
122
-
123
-func Delete(ObjectId string) {
124
-	delete(Objects, ObjectId)
125
-}
126
-`
127
-
128
-var apiControllers = `package controllers
129
-
130
-import (
131
-	"encoding/json"
132
-	"github.com/astaxie/beego"
133
-	"{{.Appname}}/models"
134
-)
135
-
136
-type ResponseInfo struct {
137
-}
138
-
139
-type ObejctController struct {
140
-	beego.Controller
141
-}
142
-
143
-func (this *ObejctController) Post() {
144
-	var ob models.Object
145
-	json.Unmarshal(this.Ctx.RequestBody, &ob)
146
-	objectid := models.AddOne(ob)
147
-	this.Data["json"] = map[string]string{"ObjectId": objectid}
148
-	this.ServeJson()
149
-}
150
-
151
-func (this *ObejctController) Get() {
152
-	objectId := this.Ctx.Params[":objectId"]
153
-	if objectId != "" {
154
-		ob, err := models.GetOne(objectId)
155
-		if err != nil {
156
-			this.Data["json"] = err
157
-		} else {
158
-			this.Data["json"] = ob
159
-		}
160
-	} else {
161
-		obs := models.GetAll()
162
-		this.Data["json"] = obs
163
-	}
164
-	this.ServeJson()
165
-}
166
-
167
-func (this *ObejctController) Put() {
168
-	objectId := this.Ctx.Params[":objectId"]
169
-	var ob models.Object
170
-	json.Unmarshal(this.Ctx.RequestBody, &ob)
171
-
172
-	err := models.Update(objectId, ob.Score)
173
-	if err != nil {
174
-		this.Data["json"] = err
175
-	} else {
176
-		this.Data["json"] = "update success!"
177
-	}
178
-	this.ServeJson()
179
-}
180
-
181
-func (this *ObejctController) Delete() {
182
-	objectId := this.Ctx.Params[":objectId"]
183
-	models.Delete(objectId)
184
-	this.Data["json"] = "delete success!"
185
-	this.ServeJson()
186
-}
187
-`
188
-
189
-func init() {
190
-	cmdApiapp.Run = createapi
191
-}
192
-
193
-func createapi(cmd *Command, args []string) {
194
-	if len(args) != 1 {
195
-		fmt.Println("error args")
196
-		os.Exit(2)
197
-	}
198
-	apppath, packpath, err := checkEnv(args[0])
199
-	if err != nil {
200
-		fmt.Println(err)
201
-		os.Exit(2)
202
-	}
203
-	os.MkdirAll(apppath, 0755)
204
-	fmt.Println("create app folder:", apppath)
205
-	os.Mkdir(path.Join(apppath, "conf"), 0755)
206
-	fmt.Println("create conf:", path.Join(apppath, "conf"))
207
-	os.Mkdir(path.Join(apppath, "controllers"), 0755)
208
-	fmt.Println("create controllers:", path.Join(apppath, "controllers"))
209
-	os.Mkdir(path.Join(apppath, "models"), 0755)
210
-	fmt.Println("create models:", path.Join(apppath, "models"))
211
-	os.Mkdir(path.Join(apppath, "tests"), 0755)
212
-	fmt.Println("create tests:", path.Join(apppath, "tests"))
213
-
214
-	fmt.Println("create conf app.conf:", path.Join(apppath, "conf", "app.conf"))
215
-	writetofile(path.Join(apppath, "conf", "app.conf"),
216
-		strings.Replace(apiconf, "{{.Appname}}", args[0], -1))
217
-
218
-	fmt.Println("create controllers default.go:", path.Join(apppath, "controllers", "default.go"))
219
-	writetofile(path.Join(apppath, "controllers", "default.go"),
220
-		strings.Replace(apiControllers, "{{.Appname}}", packpath, -1))
221
-
222
-	fmt.Println("create models object.go:", path.Join(apppath, "models", "object.go"))
223
-	writetofile(path.Join(apppath, "models", "object.go"), apiModels)
224
-
225
-	fmt.Println("create main.go:", path.Join(apppath, "main.go"))
226
-	writetofile(path.Join(apppath, "main.go"),
227
-		strings.Replace(apiMaingo, "{{.Appname}}", packpath, -1))
228
-}
229
-
230
-func checkEnv(appname string) (apppath, packpath string, err error) {
231
-	curpath, err := os.Getwd()
232
-	if err != nil {
233
-		return
234
-	}
235
-
236
-	gopath := os.Getenv("GOPATH")
237
-	Debugf("gopath:%s", gopath)
238
-	if gopath == "" {
239
-		err = fmt.Errorf("you should set GOPATH in the env")
240
-		return
241
-	}
242
-
243
-	appsrcpath := ""
244
-	haspath := false
245
-	wgopath := path.SplitList(gopath)
246
-	for _, wg := range wgopath {
247
-		wg = path.Join(wg, "src")
248
-
249
-		if path.HasPrefix(strings.ToLower(curpath), strings.ToLower(wg)) {
250
-			haspath = true
251
-			appsrcpath = wg
252
-			break
253
-		}
254
-	}
255
-
256
-	if !haspath {
257
-		err = fmt.Errorf("can't create application outside of GOPATH `%s`\n"+
258
-			"you first should `cd $GOPATH%ssrc` then use create\n", gopath, string(path.Separator))
259
-		return
260
-	}
261
-	apppath = path.Join(curpath, appname)
262
-
263
-	if _, e := os.Stat(apppath); os.IsNotExist(e) == false {
264
-		err = fmt.Errorf("path `%s` exists, can not create app without remove it\n", apppath)
265
-		return
266
-	}
267
-	packpath = strings.Join(strings.Split(apppath[len(appsrcpath)+1:], string(path.Separator)), "/")
268
-	return
269
-}
1
+// Copyright 2013 bee authors
2
+//
3
+// Licensed under the Apache License, Version 2.0 (the "License"): you may
4
+// not use this file except in compliance with the License. You may obtain
5
+// a copy of the License at
6
+//
7
+//     http://www.apache.org/licenses/LICENSE-2.0
8
+//
9
+// Unless required by applicable law or agreed to in writing, software
10
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12
+// License for the specific language governing permissions and limitations
13
+// under the License.
14
+
15
+package main
16
+
17
+import (
18
+	"fmt"
19
+	"os"
20
+	path "path/filepath"
21
+	"strings"
22
+)
23
+
24
+var cmdApiapp = &Command{
25
+	// CustomFlags: true,
26
+	UsageLine: "api [appname]",
27
+	Short:     "create an api application base on beego framework",
28
+	Long: `
29
+create an api application base on beego framework
30
+
31
+In the current path, will create a folder named [appname]
32
+
33
+In the appname folder has the follow struct:
34
+
35
+	├── conf
36
+	│   └── app.conf
37
+	├── controllers
38
+	│   └── default.go
39
+	├── main.go
40
+	└── models
41
+	    └── object.go             
42
+
43
+`,
44
+}
45
+
46
+var apiconf = `
47
+appname = {{.Appname}}
48
+httpport = 8080
49
+runmode = dev
50
+autorender = false
51
+copyrequestbody = true
52
+`
53
+var apiMaingo = `package main
54
+
55
+import (
56
+	"github.com/astaxie/beego"
57
+	"{{.Appname}}/controllers"
58
+)
59
+
60
+//		Objects
61
+
62
+//	URL					HTTP Verb				Functionality
63
+//	/object				POST					Creating Objects
64
+//	/object/<objectId>	GET						Retrieving Objects
65
+//	/object/<objectId>	PUT						Updating Objects
66
+//	/object				GET						Queries
67
+//	/object/<objectId>	DELETE					Deleting Objects
68
+
69
+func main() {
70
+	beego.RESTRouter("/object", &controllers.ObjectController{})
71
+	beego.Router("/ping", &controllers.ObjectController{},"get:Ping")
72
+	beego.Run()
73
+}
74
+`
75
+var apiModels = `package models
76
+
77
+import (
78
+	"errors"
79
+	"strconv"
80
+	"time"
81
+)
82
+
83
+var (
84
+	Objects map[string]*Object
85
+)
86
+
87
+type Object struct {
88
+	ObjectId   string
89
+	Score      int64
90
+	PlayerName string
91
+}
92
+
93
+func init() {
94
+	Objects = make(map[string]*Object)
95
+	Objects["hjkhsbnmn123"] = &Object{"hjkhsbnmn123", 100, "astaxie"}
96
+	Objects["mjjkxsxsaa23"] = &Object{"mjjkxsxsaa23", 101, "someone"}
97
+}
98
+
99
+func AddOne(object Object) (ObjectId string) {
100
+	object.ObjectId = "astaxie" + strconv.FormatInt(time.Now().UnixNano(), 10)
101
+	Objects[object.ObjectId] = &object
102
+	return object.ObjectId
103
+}
104
+
105
+func GetOne(ObjectId string) (object *Object, err error) {
106
+	if v, ok := Objects[ObjectId]; ok {
107
+		return v, nil
108
+	}
109
+	return nil, errors.New("ObjectId Not Exist")
110
+}
111
+
112
+func GetAll() map[string]*Object {
113
+	return Objects
114
+}
115
+
116
+func Update(ObjectId string, Score int64) (err error) {
117
+	if v, ok := Objects[ObjectId]; ok {
118
+		v.Score = Score
119
+		return nil
120
+	}
121
+	return errors.New("ObjectId Not Exist")
122
+}
123
+
124
+func Delete(ObjectId string) {
125
+	delete(Objects, ObjectId)
126
+}
127
+`
128
+
129
+var apiControllers = `package controllers
130
+
131
+import (
132
+	"encoding/json"
133
+	"github.com/astaxie/beego"
134
+	"{{.Appname}}/models"
135
+)
136
+
137
+type ResponseInfo struct {
138
+}
139
+
140
+type ObjectController struct {
141
+	beego.Controller
142
+}
143
+
144
+func (this *ObjectController) Post() {
145
+	var ob models.Object
146
+	json.Unmarshal(this.Ctx.Input.RequestBody, &ob)
147
+	objectid := models.AddOne(ob)
148
+	this.Data["json"] = map[string]string{"ObjectId": objectid}
149
+	this.ServeJson()
150
+}
151
+
152
+func (this *ObjectController) Get() {
153
+	objectId := this.Ctx.Input.Param[":objectId"]
154
+	if objectId != "" {
155
+		ob, err := models.GetOne(objectId)
156
+		if err != nil {
157
+			this.Data["json"] = err
158
+		} else {
159
+			this.Data["json"] = ob
160
+		}
161
+	} else {
162
+		obs := models.GetAll()
163
+		this.Data["json"] = obs
164
+	}
165
+	this.ServeJson()
166
+}
167
+
168
+func (this *ObjectController) Put() {
169
+	objectId := this.Ctx.Input.Param[":objectId"]
170
+	var ob models.Object
171
+	json.Unmarshal(this.Ctx.Input.RequestBody, &ob)
172
+
173
+	err := models.Update(objectId, ob.Score)
174
+	if err != nil {
175
+		this.Data["json"] = err
176
+	} else {
177
+		this.Data["json"] = "update success!"
178
+	}
179
+	this.ServeJson()
180
+}
181
+
182
+func (this *ObjectController) Delete() {
183
+	objectId := this.Ctx.Input.Param[":objectId"]
184
+	models.Delete(objectId)
185
+	this.Data["json"] = "delete success!"
186
+	this.ServeJson()
187
+}
188
+
189
+func (this *ObjectController) Ping() {
190
+    this.Ctx.WriteString("pong")
191
+}
192
+
193
+`
194
+
195
+var apiTests = `package tests
196
+
197
+import (
198
+    "testing"
199
+	beetest "github.com/astaxie/beego/testing"
200
+	"io/ioutil"
201
+)
202
+
203
+func TestHelloWorld(t *testing.T) {
204
+	request:=beetest.Get("/ping")
205
+	response,_:=request.Response()
206
+	defer response.Body.Close()
207
+	contents, _ := ioutil.ReadAll(response.Body)
208
+	if string(contents)!="pong"{
209
+        t.Errorf("response sould be pong")
210
+    }
211
+}
212
+
213
+`
214
+
215
+func init() {
216
+	cmdApiapp.Run = createapi
217
+}
218
+
219
+func createapi(cmd *Command, args []string) {
220
+	if len(args) != 1 {
221
+		fmt.Println("error args")
222
+		os.Exit(2)
223
+	}
224
+	apppath, packpath, err := checkEnv(args[0])
225
+	if err != nil {
226
+		fmt.Println(err)
227
+		os.Exit(2)
228
+	}
229
+	os.MkdirAll(apppath, 0755)
230
+	fmt.Println("create app folder:", apppath)
231
+	os.Mkdir(path.Join(apppath, "conf"), 0755)
232
+	fmt.Println("create conf:", path.Join(apppath, "conf"))
233
+	os.Mkdir(path.Join(apppath, "controllers"), 0755)
234
+	fmt.Println("create controllers:", path.Join(apppath, "controllers"))
235
+	os.Mkdir(path.Join(apppath, "models"), 0755)
236
+	fmt.Println("create models:", path.Join(apppath, "models"))
237
+	os.Mkdir(path.Join(apppath, "tests"), 0755)
238
+	fmt.Println("create tests:", path.Join(apppath, "tests"))
239
+
240
+	fmt.Println("create conf app.conf:", path.Join(apppath, "conf", "app.conf"))
241
+	writetofile(path.Join(apppath, "conf", "app.conf"),
242
+		strings.Replace(apiconf, "{{.Appname}}", args[0], -1))
243
+
244
+	fmt.Println("create controllers default.go:", path.Join(apppath, "controllers", "default.go"))
245
+	writetofile(path.Join(apppath, "controllers", "default.go"),
246
+		strings.Replace(apiControllers, "{{.Appname}}", packpath, -1))
247
+
248
+	fmt.Println("create tests default.go:", path.Join(apppath, "tests", "default_test.go"))
249
+	writetofile(path.Join(apppath, "tests", "default_test.go"),
250
+		apiTests)
251
+
252
+	fmt.Println("create models object.go:", path.Join(apppath, "models", "object.go"))
253
+	writetofile(path.Join(apppath, "models", "object.go"), apiModels)
254
+
255
+	fmt.Println("create main.go:", path.Join(apppath, "main.go"))
256
+	writetofile(path.Join(apppath, "main.go"),
257
+		strings.Replace(apiMaingo, "{{.Appname}}", packpath, -1))
258
+}
259
+
260
+func checkEnv(appname string) (apppath, packpath string, err error) {
261
+	curpath, err := os.Getwd()
262
+	if err != nil {
263
+		return
264
+	}
265
+
266
+	gopath := os.Getenv("GOPATH")
267
+	Debugf("gopath:%s", gopath)
268
+	if gopath == "" {
269
+		err = fmt.Errorf("you should set GOPATH in the env")
270
+		return
271
+	}
272
+
273
+	appsrcpath := ""
274
+	haspath := false
275
+	wgopath := path.SplitList(gopath)
276
+	for _, wg := range wgopath {
277
+		wg = path.Join(wg, "src")
278
+
279
+		if path.HasPrefix(strings.ToLower(curpath), strings.ToLower(wg)) {
280
+			haspath = true
281
+			appsrcpath = wg
282
+			break
283
+		}
284
+	}
285
+
286
+	if !haspath {
287
+		err = fmt.Errorf("can't create application outside of GOPATH `%s`\n"+
288
+			"you first should `cd $GOPATH%ssrc` then use create\n", gopath, string(path.Separator))
289
+		return
290
+	}
291
+	apppath = path.Join(curpath, appname)
292
+
293
+	if _, e := os.Stat(apppath); os.IsNotExist(e) == false {
294
+		err = fmt.Errorf("path `%s` exists, can not create app without remove it\n", apppath)
295
+		return
296
+	}
297
+	packpath = strings.Join(strings.Split(apppath[len(appsrcpath)+1:], string(path.Separator)), "/")
298
+	return
299
+}

+ 57
- 57
new.go View File

@@ -122,7 +122,7 @@ func createApp(cmd *Command, args []string) {
122 122
 	writetofile(path.Join(apppath, "views", "index.tpl"), indextpl)
123 123
 
124 124
 	fmt.Println(path.Join(apppath, "main.go"))
125
-	writetofile(path.Join(apppath, "main.go"), strings.Replace(maingo, "{{.Appname}}", strings.Join(strings.Split(apppath[len(appsrcpath)+1:], string(path.Separator)), string(path.Separator)), -1))
125
+	writetofile(path.Join(apppath, "main.go"), strings.Replace(maingo, "{{.Appname}}", strings.Join(strings.Split(apppath[len(appsrcpath)+1:], string(path.Separator)), "/"), -1))
126 126
 
127 127
 	ColorLog("[SUCC] New application successfully created!\n")
128 128
 }
@@ -168,62 +168,62 @@ var indextpl = `<!DOCTYPE html>
168 168
   	<head>
169 169
     	<title>Beego</title>
170 170
     	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
171
-  	</head>
172 171
 	
173
-	<style type="text/css">
174
-		body {
175
-			margin: 0px;
176
-			font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
177
-			font-size: 14px;
178
-			line-height: 20px;
179
-			color: rgb(51, 51, 51);
180
-			background-color: rgb(255, 255, 255);
181
-		}
182
-
183
-		.hero-unit {
184
-			padding: 60px;
185
-			margin-bottom: 30px;
186
-			border-radius: 6px 6px 6px 6px;
187
-		}
188
-
189
-		.container {
190
-			width: 940px;
191
-			margin-right: auto;
192
-			margin-left: auto;
193
-		}
194
-
195
-		.row {
196
-			margin-left: -20px;
197
-		}
198
-
199
-		h1 {
200
-			margin: 10px 0px;
201
-			font-family: inherit;
202
-			font-weight: bold;
203
-			text-rendering: optimizelegibility;
204
-		}
205
-
206
-		.hero-unit h1 {
207
-			margin-bottom: 0px;
208
-			font-size: 60px;
209
-			line-height: 1;
210
-			letter-spacing: -1px;
211
-			color: inherit;
212
-		}
213
-
214
-		.description {
215
-		    padding-top: 5px;
216
-		    padding-left: 5px;
217
-		    font-size: 18px;
218
-		    font-weight: 200;
219
-		    line-height: 30px;
220
-		    color: inherit;
221
-		}
222
-
223
-		p {
224
-		    margin: 0px 0px 10px;
225
-		}
226
-	</style>
172
+		<style type="text/css">
173
+			body {
174
+				margin: 0px;
175
+				font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
176
+				font-size: 14px;
177
+				line-height: 20px;
178
+				color: rgb(51, 51, 51);
179
+				background-color: rgb(255, 255, 255);
180
+			}
181
+
182
+			.hero-unit {
183
+				padding: 60px;
184
+				margin-bottom: 30px;
185
+				border-radius: 6px 6px 6px 6px;
186
+			}
187
+
188
+			.container {
189
+				width: 940px;
190
+				margin-right: auto;
191
+				margin-left: auto;
192
+			}
193
+
194
+			.row {
195
+				margin-left: -20px;
196
+			}
197
+
198
+			h1 {
199
+				margin: 10px 0px;
200
+				font-family: inherit;
201
+				font-weight: bold;
202
+				text-rendering: optimizelegibility;
203
+			}
204
+
205
+			.hero-unit h1 {
206
+				margin-bottom: 0px;
207
+				font-size: 60px;
208
+				line-height: 1;
209
+				letter-spacing: -1px;
210
+				color: inherit;
211
+			}
212
+
213
+			.description {
214
+				padding-top: 5px;
215
+				padding-left: 5px;
216
+				font-size: 18px;
217
+				font-weight: 200;
218
+				line-height: 30px;
219
+				color: inherit;
220
+			}
221
+
222
+			p {
223
+				margin: 0px 0px 10px;
224
+			}
225
+		</style>
226
+	</head>
227 227
   	
228 228
   	<body>
229 229
   		<header class="hero-unit" style="background-color:#A9F16C">
@@ -236,7 +236,7 @@ var indextpl = `<!DOCTYPE html>
236 236
 			    <br />
237 237
 			    	Official website: <a href="http://{{.Website}}">{{.Website}}</a>
238 238
 			    <br />
239
-			    	Contact me: {{.Email}}</a>
239
+			    	Contact me: {{.Email}}
240 240
 			    </p>
241 241
 			  </div>
242 242
 			</div>

+ 27
- 14
test.go View File

@@ -15,7 +15,6 @@
15 15
 package main
16 16
 
17 17
 import (
18
-	"bytes"
19 18
 	"os"
20 19
 	"os/exec"
21 20
 	path "path/filepath"
@@ -32,6 +31,20 @@ func init() {
32 31
 	cmdTest.Run = testApp
33 32
 }
34 33
 
34
+func safePathAppend(arr []string, paths ...string) []string {
35
+	for _, path := range paths {
36
+		if pathExists(path) {
37
+			arr = append(arr, path)
38
+		}
39
+	}
40
+	return arr
41
+}
42
+
43
+func pathExists(path string) bool {
44
+	_, err := os.Stat(path)
45
+	return err == nil || os.IsExist(err)
46
+}
47
+
35 48
 var started = make(chan bool)
36 49
 
37 50
 func testApp(cmd *Command, args []string) {
@@ -48,7 +61,7 @@ func testApp(cmd *Command, args []string) {
48 61
 		ColorLog("[ERRO] Fail to parse bee.json[ %s ]\n", err)
49 62
 	}
50 63
 	var paths []string
51
-	paths = append(paths,
64
+	paths = safePathAppend(paths,
52 65
 		path.Join(crupath, conf.DirStruct.Controllers),
53 66
 		path.Join(crupath, conf.DirStruct.Models),
54 67
 		path.Join(crupath, "./")) // Current path.
@@ -63,28 +76,28 @@ func testApp(cmd *Command, args []string) {
63 76
 		select {
64 77
 		case <-started:
65 78
 			runTest()
66
-			Kill()
67
-			os.Exit(0)
79
+			//Kill()
80
+			//os.Exit(0)
68 81
 		}
69 82
 	}
70 83
 }
71 84
 
72 85
 func runTest() {
73 86
 	ColorLog("[INFO] Start testing...\n")
74
-	time.Sleep(time.Second * 5)
75
-	path, _ := os.Getwd()
76
-	os.Chdir(path + "/tests")
87
+	time.Sleep(time.Second * 1)
88
+	crupwd, _ := os.Getwd()
89
+	testDir := path.Join(crupwd, "tests")
90
+	if pathExists(testDir) {
91
+		os.Chdir(testDir)
92
+	}
77 93
 
78 94
 	var err error
79 95
 	icmd := exec.Command("go", "test")
80
-	var out, errbuffer bytes.Buffer
81
-	icmd.Stdout = &out
82
-	icmd.Stderr = &errbuffer
83
-	ColorLog("[INFO] ============== Test Begin ===================\n")
96
+	icmd.Stdout = os.Stdout
97
+	icmd.Stderr = os.Stderr
98
+	ColorLog("[TRAC] ============== Test Begin ===================\n")
84 99
 	err = icmd.Run()
85
-	ColorLog(out.String())
86
-	ColorLog(errbuffer.String())
87
-	ColorLog("[INFO] ============== Test End ===================\n")
100
+	ColorLog("[TRAC] ============== Test End ===================\n")
88 101
 
89 102
 	if err != nil {
90 103
 		ColorLog("[ERRO] ============== Test failed ===================\n")

+ 12
- 6
util.go View File

@@ -20,6 +20,7 @@ import (
20 20
 	"path/filepath"
21 21
 	"runtime"
22 22
 	"strings"
23
+	"time"
23 24
 )
24 25
 
25 26
 // Go is a basic promise implementation: it wraps calls a function in a goroutine
@@ -55,6 +56,11 @@ const (
55 56
 	Magenta
56 57
 	//NRed      = uint8(31) // Normal
57 58
 	EndColor = "\033[0m"
59
+
60
+	TRAC = "TRAC"
61
+	ERRO = "ERRO"
62
+	WARN = "WARN"
63
+	SUCC = "SUCC"
58 64
 )
59 65
 
60 66
 // ColorLog colors log and print to stdout.
@@ -78,7 +84,6 @@ func ColorLogS(format string, a ...interface{}) string {
78 84
 	var clog string
79 85
 
80 86
 	if runtime.GOOS != "windows" {
81
-
82 87
 		// Level.
83 88
 		i := strings.Index(log, "]")
84 89
 		if log[0] == '[' && i > -1 {
@@ -125,20 +130,21 @@ func ColorLogS(format string, a ...interface{}) string {
125 130
 		log = clog + log
126 131
 	}
127 132
 
128
-	return log
133
+	return strings.TrimPrefix(
134
+		time.Now().Format("2006-01-02 03:04:05 "), "20") + log
129 135
 }
130 136
 
131 137
 // getColorLevel returns colored level string by given level.
132 138
 func getColorLevel(level string) string {
133 139
 	level = strings.ToUpper(level)
134 140
 	switch level {
135
-	case "TRAC":
141
+	case TRAC:
136 142
 		return fmt.Sprintf("\033[%dm%s\033[0m", Blue, level)
137
-	case "ERRO":
143
+	case ERRO:
138 144
 		return fmt.Sprintf("\033[%dm%s\033[0m", Red, level)
139
-	case "WARN":
145
+	case WARN:
140 146
 		return fmt.Sprintf("\033[%dm%s\033[0m", Magenta, level)
141
-	case "SUCC":
147
+	case SUCC:
142 148
 		return fmt.Sprintf("\033[%dm%s\033[0m", Green, level)
143 149
 	default:
144 150
 		return level

+ 2
- 3
watch.go View File

@@ -16,7 +16,6 @@ package main
16 16
 
17 17
 import (
18 18
 	"fmt"
19
-	"log"
20 19
 	"os"
21 20
 	"os/exec"
22 21
 	"strings"
@@ -66,7 +65,7 @@ func NewWatcher(paths []string) {
66 65
 					go Autobuild()
67 66
 				}
68 67
 			case err := <-watcher.Error:
69
-				log.Fatal("error:", err)
68
+				ColorLog("[WARN] %s\n", err.Error()) // No need to exit here
70 69
 			}
71 70
 		}
72 71
 
@@ -143,7 +142,7 @@ func Kill() {
143 142
 			fmt.Println("Kill -> ", e)
144 143
 		}
145 144
 	}()
146
-	if cmd != nil {
145
+	if cmd != nil && cmd.Process != nil {
147 146
 		cmd.Process.Kill()
148 147
 	}
149 148
 }

Loading…
Cancel
Save