go-macaron / macaron Goto Github PK
View Code? Open in Web Editor NEWPackage macaron is a high productive and modular web framework in Go.
Home Page: https://go-macaron.com
License: Apache License 2.0
Package macaron is a high productive and modular web framework in Go.
Home Page: https://go-macaron.com
License: Apache License 2.0
现在的路由是不是有BUG?
以前我这样的Post的请求是生效的,在url里面还可以跟参数
m.Post("/searchCategory2Json/:category:string", searchCategoryJsonAction)
但是最近更新了macaron之后,这样的Post请求就无法走到searchCategoryJsonAction方法里去了
和beego里的这个等效:
self.Data["usersonline"] = beego.GlobalSessions.GetActiveSession()
It appears to be virtually identical to https://github.com/codegangsta/inject/blob/master/inject.go (Copyright (c) 2013 Jeremy Saenz), MIT-licensed, which requires that "The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software."
Hi, macaron
quite cool compared to martini
and negroni
, but there are something lacking, that is oauth-plugin, the other two has it (github.com/martini-contrib/oauth2
and github.com/GoIncremental/negroni-oauth2
) but macaron
doesn't have it.
并发200条,Martini 都没什么损失,Macaron就损失了1/4。
并发1000时,Macaron内存会暴涨到1G,Martini 才不到300M。
因为是产品不能发上来,基本上替换的部分,都是获取值的部分,没什么大变化,都开启压缩。
idStr := params["id"]
id, err := strconv.ParseInt(idStr, 10, 64)
if err != nil {
r.Data(200, []byte("Port nil"))
return
}
to
id := ctx.ParamsInt64(":id")
if id == 0 {
ctx.RawData(200, []byte("Port error"))
return
}
测试程序
package main
import (
"io/ioutil"
"math/rand"
"net/http"
"net/url"
"strconv"
"time"
)
func main() {
key := rand.New(rand.NewSource(time.Now().UnixNano()))
for i := 0; i < 1000; i++ {
go todo(key)
}
select {}
}
func todo(key *rand.Rand) {
host := "http://127.0.0.1/port/1"
num := "test" + strconv.Itoa(key.Intn(100000000))
link, err := url.Parse(host)
if err != nil {
return
}
parameters := link.Query()
parameters.Add("num", num)
link.RawQuery = parameters.Encode()
httpGet(link.String())
}
func httpGet(url string) string {
timeout := time.Duration(30 * time.Second)
client := http.Client{
Timeout: timeout,
}
resp, err := client.Get(url)
if err != nil {
return ""
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
resp.Body.Close()
return ""
}
resp.Body.Close()
return string(body)
}
封装下,取值更加方便
好像是调用 ctx.JSON 或者 ctx.Status 的时候,shell会打印出来。
http: multiple response.WriteHeader calls 在 Go\src\net\http\server.go 的 WriteHeader 中。
修复下
密钥Secret没有用于对value的编码中,没有起到盐值的作用,因为是开源的,看过代码的都可以根据密文VW5rbndvbg==|1419425690450651400|31357785f307e5f3945189009e8dfb7ecf23ab37中的VW5rbndvbg==反译出来。
vs, _ := base64.URLEncoding.DecodeString("VW5rbndvbg==")
string(vs) == “Unknwon”
要安全就不要用Base64,采用AES算法吧
//////////////////////////////////////////////////////////////////////////////////////////////////
// SetSuperSecureCookie sets given cookie value to response header with secret string.
func (ctx *Context) SetSuperSecureCookie(Secret, name, value string, others ...interface{}) {
vs := base64.URLEncoding.EncodeToString([]byte(value))
timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
h := hmac.New(sha1.New, []byte(Secret))
fmt.Fprintf(h, "%s%s", vs, timestamp)
sig := fmt.Sprintf("%02x", h.Sum(nil))
cookie := strings.Join([]string{vs, timestamp, sig}, "|")
ctx.SetCookie(name, cookie, others...)
}
in 验证是否在某个范围内
notin 验证是否不在某个范围内
/user/list/?:page:int 这种无法匹配到/usr/list/, 只能匹配到 /usr/list/123 这种
Hi,
Did you have a chance to read
http://codegangsta.io/blog/2014/05/19/my-thoughts-on-martini/
https://github.com/zenazn/goji
Thx for gogs, it's great :)
https://github.com/fex-team/fis 是来自百度的前端框架工具,已经有朋友把它做成了matini的中间件,其用法示例在:https://github.com/xiangshouding/martini-fis-app 。
当时看到这个工具时一时兴起就在群里提了一下,仔细看了用法示例,又在想这种修改模板引擎,植入前端框架的功能的做法是不是有些偏门,原matini集成项目貌似好久都没有维护更新过了。我个人还是喜欢前后端完全分离,这样更合乎软件的正交。
很喜欢百度的一些前端工具,如fis/echarts,如果能够更好的和macaron结合自然是很美好的事。烦请无闻老师帮忙分析一下利弊:有没有必要做这么一个中间件,其优势在哪。
macaron的二进制文件保存没有封装方法,而beego有一个SaveToFile: https://github.com/astaxie/beego/blob/master/controller.go (539行)。建议添加一个。
Is there any way to add custom 500 page? Or any error page besides 404?
用 https://github.com/martini-contrib/method 发现还是无法用Put或者Patch方法,自己用中间件方法
const (
HTTPMethodOverrideHeader = "X-HTTP-Method-Override"
HTTPMethodOverrideFormKey = "_method"
)
m := macaron.Classic()
m.Use(func(w http.ResponseWriter, r *http.Request) {
om := r.FormValue(HTTPMethodOverrideFormKey)
if r.Method == "POST" {
if om == "" {
om = r.Header.Get(HTTPMethodOverrideHeader)
}
if om == "PUT" || om == "PATCH" || om == "DELETE" {
r.Method = om
}
}
})
也无法覆盖,发现只有在macaron的源代码中https://github.com/Unknwon/macaron/blob/master/router.go#L235 进行处理才有用
const (
HTTPMethodOverrideHeader = "X-HTTP-Method-Override"
HTTPMethodOverrideFormKey = "_method"
)
func (r *Router) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
om := r.FormValue(HTTPMethodOverrideFormKey)
if r.Method == "POST" {
if om == "" {
om = r.Header.Get(HTTPMethodOverrideHeader)
}
if om == "PUT" || om == "PATCH" || om == "DELETE" {
r.Method = om
}
}
if t, ok := r.routers[req.Method]; ok {
h, p := t.Match(req.URL.Path)
if h != nil {
if splat, ok := p[":splat"]; ok {
p["*"] = p[":splat"] // Better name.
splatlist := strings.Split(splat, "/")
for k, v := range splatlist {
p[com.ToStr(k)] = v
}
}
h(rw, req, p)
return
}
}
r.notFound(rw, req)
}
建议使用github.com/go-ini/ini的引用方式使用,否则经常会拉不下来...
m.Group("", func(r *macaron.Router)
r和m效果一样 所以 需要的时候再自行导入吧 这m.Group中的入口参数不要成为必须品
m.Get("/", Gethello)
func GetHello() string {
return "hello world"
}
这样是OK的。
但是 这样写
m.Get("/", Gethello())
是可以编译通过的 但是运行不了. 应该是在编译的时候需要了对 route的函数做验证。
As document mentions:
Matching priority of same pattern is first add first match.
But in this case:
/user/:uid/:name1/:name2/hit
/user/:uid/:name1/hit
and first router will never hit.
if change Placeholders to regex also not working:
/user/:uid/:name1/([0-9]+)/hit
/user/:uid/:name1/hit
http://gorevel.cn/docs/manual/routing.html 反转路由 Macaron 现在有实现的办法吗
无闻.。 10/19/2014 11:12:23 PM
就是用一个路由文件来自动注册路由?
无闻.。 10/19/2014 11:12:27 PM
revel这样的?
最美不过相识
10/19/2014 11:12:51 PM
用路由文件生成访问路由的urls
无闻.。 10/19/2014 11:13:06 PM
从技术角度来说。。可以实现啊。。
无闻.。 10/19/2014 11:13:19 PM
但是有个问题啊。。
无闻.。 10/19/2014 11:13:20 PM
额。。
最美不过相识
10/19/2014 11:13:20 PM
c.Redirect(routes.App.ViewForm(username))
11:13:34 PM
无闻.。 10/19/2014 11:13:34 PM
macaron好像没有控制器这一说。。
最美不过相识
10/19/2014 11:13:50 PM
c.Redirect("/user")
不用这样写了
无闻.。 10/19/2014 11:14:45 PM
让我思考思考。。。
无闻.。 10/19/2014 11:14:54 PM
最美不过相识
10/19/2014 11:14:52 PM
也就是用beego的urlfor 根据路由的规则生成urls
最美不过相识
10/19/2014 11:15:03 PM
http://beego.me/docs/mvc/controller/urlbuilding.md
无闻.。 10/19/2014 11:15:08 PM
macaron没控制器一说。。
最美不过相识
10/19/2014 11:15:08 PM
嗯,这个你比我了解
无闻.。 10/19/2014 11:15:13 PM
全都是函数。。
11:15:48 PM
最美不过相识
10/19/2014 11:15:48 PM
UrlFor("TestController.Get", ":last", "xie", ":first", "asta")
// 输出 /person/xie/asta
这样可好实现?
无闻.。 10/19/2014 11:16:26 PM
如果说是,给每个路由一个名称的话,倒是好像可以
github.com/beatrichartz/martini-sockets
normally in Go code you can just import _ "expvar"
which adds a http handler directly , listening on /debug/vars
(see http://golang.org/pkg/expvar/)
However, when using macaron, this route is hidden and 404's.
i have used github.com/macaron-contrib/toolbox which solves a similar problem for /debug/pprof
but I couldn't find the solution for expvars.
thanks.
package main
import (
"github.com/Unknwon/macaron"
)
func main() {
m := macaron.Classic()
m.Get("/", func(ctx *macaron.Context) {
ctx.Redirect("http://www.yougam.com/")
})
m.Run()
}
这段代码会报错.
render也是有跳转的,所以标题写迁移可能不太对,复制个吧...
我看了源代码,binding.Json() 执行后 是把请求里的body存入到context中了 ,我该怎么去重新拿到这些数据
router.go的type Router 的prefx字段拼写错误,正确拼写应为prefix
建议表单验证能为一些不是必须填写的字段设置默认值
m := macaron.Classic()
m.Use(macaron.Static("views"))
m.Run()
views下有文件join.html
http://localhost:3000/join.html访问报404
现在macaron
注册的方式为:
m := macaron.New()
m.Use(macaron.Static("public"))
so easy!再注册一个m.Use(macaron.Static("assets"))
,能更easy吗?比如:
m.Use(macaron.Static("public,assets,..."))
当然这样StaticOptions就冲突了,但是更多的情况是StaticOptions较少应用或者更多的只用一次,可否考虑macaron.Static(staticOpt StaticOptions,directory ...string)或者再考虑多的方法
I am fairly new at Go and Macaron, but I have a question regarding setting response headers.
func main() {
m := macaron.Classic()
m.Use(func(ctx *macaron.Context) {
ctx.Resp.Header.Set('key', value);
})
}
But I get an error: ctx.Resp.Header.Set undefined (type func() http.Header has no field or method Set)
What have I done wrong?
Thanks!
ctx.SetParams("name","value")
m.Get(`/:user([a-zA-Z0-9][-a-zA-Z0-9]+)/:version(v0|v[1-9][0-9]*)/:name([a-zA-Z][-a-zA-Z0-9]*):subPath((/[a-zA-Z][-a-zA-Z0-9]*)*)`, head)
Match ex:
Bluek404/v1/test/xx/xx/xxxxx/xxxxx
I love macaron but the docs/getting started needs a little help. I learned and got started mostly from reading the gogs source code. What do you think about adding generators like ruby on rails does to help people get started? I think this would be a great differentiator as well for the project.
macaron new todo
todo/
models/
lib/
views/
routers/
todo.go
macaron gen route users
todo/
models/user.go
routers/user.go
views/user/*.html
etc.
Is there a way to use dynamic subdomains in Macaron?
E.g. calling sub1.mydomain.com would trigger its handler, and sub2.mydomain.com another - but the thing is to match these subdomains dynamically.
类似beego里的GetFile
file, handler, e := self.GetFile("avatar")
Like go-restful built-in Swagger integration. Auto-generated documentation with Swagger is pretty awesome. And you can auto-generate API clients for lots of different languages.
Further on, it is possible to generate code with Swagger json defines.
strings.TrimSpace(ctx.Query("name")) 这样太麻烦了
如果用URL参数自定义切换主题,用户修改URL参数弄个不存在的主题名,那程序就出错了.
Solved
[杭州]无闻
2014/10/15 12:53:38
修改中间件是可以的,不过中间件没开放这个API给你
[广州]正雄 2014/10/15 12:54:24
那 能不能暴露出这个api?让我能在程序运行过程中改模板和静态路径
[广州]正雄 2014/10/15 12:54:49
然后改完后 他会重新缓存一次神马的 大概是这么想
[杭州]无闻
2014/10/15 12:55:08
嗯
[杭州]无闻
2014/10/15 12:55:12
你提个issue
[广州]正雄 2014/10/15 12:55:18
好
https://github.com/martini-contrib/sessionauth
目前是否有类似这样的东西呢?
While reviewing my code (before moving it to another framework) I noticed that the context are somewhat broken. When you attempt to redirect, it does complete the redirection but it does not yield at that point but continue on down the nest until the end of that specific scope, which does cause many problems.
取值方便点
新建文件public/index.html
直接输入localhost:xxx 访问报404错误
I have been using macaron for a production app for awhile and I'm getting 404's if i click links too quickly.
可以定义个 message 字段来定义
https://github.com/ascoders/alipay
https://github.com/nareix/alipay
看看能不能把这些改一个支付宝中间件出来,有利于推广Macaron.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.