pax_global_header 0000666 0000000 0000000 00000000064 12654131704 0014515 g ustar 00root root 0000000 0000000 52 comment=26c1cde6f1acba6ec0a54547d68ef575559348f1 macaron-1/ 0000775 0000000 0000000 00000000000 12654131704 0012637 5 ustar 00root root 0000000 0000000 macaron-1/.gitignore 0000664 0000000 0000000 00000000061 12654131704 0014624 0 ustar 00root root 0000000 0000000 macaron.sublime-project macaron.sublime-workspace macaron-1/.travis.yml 0000664 0000000 0000000 00000000200 12654131704 0014740 0 ustar 00root root 0000000 0000000 sudo: false language: go go: - 1.3 - 1.4 - 1.5 script: go test -v -cover -race notifications: email: - u@gogs.io macaron-1/LICENSE 0000664 0000000 0000000 00000024041 12654131704 0013645 0 ustar 00root root 0000000 0000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: You must give any other recipients of the Work or Derivative Works a copy of this License; and You must cause any modified files to carry prominent notices stating that You changed the files; and You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. macaron-1/README.md 0000664 0000000 0000000 00000007616 12654131704 0014130 0 ustar 00root root 0000000 0000000 Macaron [](https://travis-ci.org/go-macaron/macaron) [](http://gocover.io/github.com/go-macaron/macaron) =======================  Package macaron is a high productive and modular web framework in Go. ##### Current version: 1.0.0 ## Getting Started The minimum requirement of Go is **1.3**. To install Macaron: go get gopkg.in/macaron.v1 The very basic usage of Macaron: ```go package main import "gopkg.in/macaron.v1" func main() { m := macaron.Classic() m.Get("/", func() string { return "Hello world!" }) m.Run() } ``` ## Features - Powerful routing with suburl. - Flexible routes combinations. - Unlimited nested group routers. - Directly integrate with existing services. - Dynamically change template files at runtime. - Allow to use in-memory template and static files. - Easy to plugin/unplugin features with modular design. - Handy dependency injection powered by [inject](https://github.com/codegangsta/inject). - Better router layer and less reflection make faster speed. ## Middlewares Middlewares allow you easily plugin/unplugin features for your Macaron applications. There are already many [middlewares](https://github.com/go-macaron) to simplify your work: - render - Go template engine - static - Serves static files - [gzip](https://github.com/go-macaron/gzip) - Gzip compression to all responses - [binding](https://github.com/go-macaron/binding) - Request data binding and validation - [i18n](https://github.com/go-macaron/i18n) - Internationalization and Localization - [cache](https://github.com/go-macaron/cache) - Cache manager - [session](https://github.com/go-macaron/session) - Session manager - [csrf](https://github.com/go-macaron/csrf) - Generates and validates csrf tokens - [captcha](https://github.com/go-macaron/captcha) - Captcha service - [pongo2](https://github.com/go-macaron/pongo2) - Pongo2 template engine support - [sockets](https://github.com/go-macaron/sockets) - WebSockets channels binding - [bindata](https://github.com/go-macaron/bindata) - Embed binary data as static and template files - [toolbox](https://github.com/go-macaron/toolbox) - Health check, pprof, profile and statistic services - [oauth2](https://github.com/go-macaron/oauth2) - OAuth 2.0 backend - [switcher](https://github.com/go-macaron/switcher) - Multiple-site support - [method](https://github.com/go-macaron/method) - HTTP method override - [permissions2](https://github.com/xyproto/permissions2) - Cookies, users and permissions - [renders](https://github.com/go-macaron/renders) - Beego-like render engine(Macaron has built-in template engine, this is another option) ## Use Cases - [Gogs](https://gogs.io): A painless self-hosted Git Service - [Peach](https://peachdocs.org): A modern web documentation server - [Go Walker](https://gowalker.org): Go online API documentation - [Switch](https://gopm.io): Gopm registry - [YouGam](http://yougam.com): Online Forum - [Critical Stack Intel](https://intel.criticalstack.com/): A 100% free intel marketplace from Critical Stack, Inc. ## Getting Help - [API Reference](https://gowalker.org/gopkg.in/macaron.v1) - [Documentation](https://go-macaron.com) - [FAQs](https://go-macaron.com/docs/faqs) - [](https://gitter.im/go-macaron/macaron?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) ## Credits - Basic design of [Martini](https://github.com/go-martini/martini). - Logo is modified by [@insionng](https://github.com/insionng) based on [Tribal Dragon](http://xtremeyamazaki.deviantart.com/art/Tribal-Dragon-27005087). ## License This project is under the Apache License, Version 2.0. See the [LICENSE](LICENSE) file for the full license text. macaron-1/context.go 0000664 0000000 0000000 00000031446 12654131704 0014662 0 ustar 00root root 0000000 0000000 // Copyright 2014 The Macaron Authors // // Licensed under the Apache License, Version 2.0 (the "License"): you may // not use this file except in compliance with the License. You may obtain // a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations // under the License. package macaron import ( "crypto/md5" "encoding/hex" "html/template" "io" "io/ioutil" "mime/multipart" "net/http" "net/url" "os" "path" "path/filepath" "reflect" "strconv" "strings" "time" "github.com/Unknwon/com" "github.com/go-macaron/inject" ) // Locale reprents a localization interface. type Locale interface { Language() string Tr(string, ...interface{}) string } // RequestBody represents a request body. type RequestBody struct { reader io.ReadCloser } // Bytes reads and returns content of request body in bytes. func (rb *RequestBody) Bytes() ([]byte, error) { return ioutil.ReadAll(rb.reader) } // String reads and returns content of request body in string. func (rb *RequestBody) String() (string, error) { data, err := rb.Bytes() return string(data), err } // ReadCloser returns a ReadCloser for request body. func (rb *RequestBody) ReadCloser() io.ReadCloser { return rb.reader } // Request represents an HTTP request received by a server or to be sent by a client. type Request struct { *http.Request } func (r *Request) Body() *RequestBody { return &RequestBody{r.Request.Body} } // Context represents the runtime context of current request of Macaron instance. // It is the integration of most frequently used middlewares and helper methods. type Context struct { inject.Injector handlers []Handler action Handler index int *Router Req Request Resp ResponseWriter params Params Render Locale Data map[string]interface{} } func (c *Context) handler() Handler { if c.index < len(c.handlers) { return c.handlers[c.index] } if c.index == len(c.handlers) { return c.action } panic("invalid index for context handler") } func (c *Context) Next() { c.index += 1 c.run() } func (c *Context) Written() bool { return c.Resp.Written() } func (c *Context) run() { for c.index <= len(c.handlers) { vals, err := c.Invoke(c.handler()) if err != nil { panic(err) } c.index += 1 // if the handler returned something, write it to the http response if len(vals) > 0 { ev := c.GetVal(reflect.TypeOf(ReturnHandler(nil))) handleReturn := ev.Interface().(ReturnHandler) handleReturn(c, vals) } if c.Written() { return } } } // RemoteAddr returns more real IP address. func (ctx *Context) RemoteAddr() string { addr := ctx.Req.Header.Get("X-Real-IP") if len(addr) == 0 { addr = ctx.Req.Header.Get("X-Forwarded-For") if addr == "" { addr = ctx.Req.RemoteAddr if i := strings.LastIndex(addr, ":"); i > -1 { addr = addr[:i] } } } return addr } func (ctx *Context) renderHTML(status int, setName, tplName string, data ...interface{}) { if len(data) <= 0 { ctx.Render.HTMLSet(status, setName, tplName, ctx.Data) } else if len(data) == 1 { ctx.Render.HTMLSet(status, setName, tplName, data[0]) } else { ctx.Render.HTMLSet(status, setName, tplName, data[0], data[1].(HTMLOptions)) } } // HTML calls Render.HTML but allows less arguments. func (ctx *Context) HTML(status int, name string, data ...interface{}) { ctx.renderHTML(status, _DEFAULT_TPL_SET_NAME, name, data...) } // HTML calls Render.HTMLSet but allows less arguments. func (ctx *Context) HTMLSet(status int, setName, tplName string, data ...interface{}) { ctx.renderHTML(status, setName, tplName, data...) } func (ctx *Context) Redirect(location string, status ...int) { code := http.StatusFound if len(status) == 1 { code = status[0] } http.Redirect(ctx.Resp, ctx.Req.Request, location, code) } // Maximum amount of memory to use when parsing a multipart form. // Set this to whatever value you prefer; default is 10 MB. var MaxMemory = int64(1024 * 1024 * 10) func (ctx *Context) parseForm() { if ctx.Req.Form != nil { return } contentType := ctx.Req.Header.Get(_CONTENT_TYPE) if (ctx.Req.Method == "POST" || ctx.Req.Method == "PUT") && len(contentType) > 0 && strings.Contains(contentType, "multipart/form-data") { ctx.Req.ParseMultipartForm(MaxMemory) } else { ctx.Req.ParseForm() } } // Query querys form parameter. func (ctx *Context) Query(name string) string { ctx.parseForm() return ctx.Req.Form.Get(name) } // QueryTrim querys and trims spaces form parameter. func (ctx *Context) QueryTrim(name string) string { return strings.TrimSpace(ctx.Query(name)) } // QueryStrings returns a list of results by given query name. func (ctx *Context) QueryStrings(name string) []string { ctx.parseForm() vals, ok := ctx.Req.Form[name] if !ok { return []string{} } return vals } // QueryEscape returns escapred query result. func (ctx *Context) QueryEscape(name string) string { return template.HTMLEscapeString(ctx.Query(name)) } // QueryInt returns query result in int type. func (ctx *Context) QueryInt(name string) int { return com.StrTo(ctx.Query(name)).MustInt() } // QueryInt64 returns query result in int64 type. func (ctx *Context) QueryInt64(name string) int64 { return com.StrTo(ctx.Query(name)).MustInt64() } // QueryFloat64 returns query result in float64 type. func (ctx *Context) QueryFloat64(name string) float64 { v, _ := strconv.ParseFloat(ctx.Query(name), 64) return v } // Params returns value of given param name. // e.g. ctx.Params(":uid") or ctx.Params("uid") func (ctx *Context) Params(name string) string { if len(name) == 0 { return "" } if len(name) > 1 && name[0] != ':' { name = ":" + name } return ctx.params[name] } // SetParams sets value of param with given name. func (ctx *Context) SetParams(name, val string) { if !strings.HasPrefix(name, ":") { name = ":" + name } ctx.params[name] = val } // ParamsEscape returns escapred params result. // e.g. ctx.ParamsEscape(":uname") func (ctx *Context) ParamsEscape(name string) string { return template.HTMLEscapeString(ctx.Params(name)) } // ParamsInt returns params result in int type. // e.g. ctx.ParamsInt(":uid") func (ctx *Context) ParamsInt(name string) int { return com.StrTo(ctx.Params(name)).MustInt() } // ParamsInt64 returns params result in int64 type. // e.g. ctx.ParamsInt64(":uid") func (ctx *Context) ParamsInt64(name string) int64 { return com.StrTo(ctx.Params(name)).MustInt64() } // ParamsFloat64 returns params result in int64 type. // e.g. ctx.ParamsFloat64(":uid") func (ctx *Context) ParamsFloat64(name string) float64 { v, _ := strconv.ParseFloat(ctx.Params(name), 64) return v } // GetFile returns information about user upload file by given form field name. func (ctx *Context) GetFile(name string) (multipart.File, *multipart.FileHeader, error) { return ctx.Req.FormFile(name) } // SaveToFile reads a file from request by field name and saves to given path. func (ctx *Context) SaveToFile(name, savePath string) error { fr, _, err := ctx.GetFile(name) if err != nil { return err } defer fr.Close() fw, err := os.OpenFile(savePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666) if err != nil { return err } defer fw.Close() _, err = io.Copy(fw, fr) return err } // SetCookie sets given cookie value to response header. // FIXME: IE support? http://golanghome.com/post/620#reply2 func (ctx *Context) SetCookie(name string, value string, others ...interface{}) { cookie := http.Cookie{} cookie.Name = name cookie.Value = url.QueryEscape(value) if len(others) > 0 { switch v := others[0].(type) { case int: cookie.MaxAge = v case int64: cookie.MaxAge = int(v) case int32: cookie.MaxAge = int(v) } } cookie.Path = "/" if len(others) > 1 { if v, ok := others[1].(string); ok && len(v) > 0 { cookie.Path = v } } if len(others) > 2 { if v, ok := others[2].(string); ok && len(v) > 0 { cookie.Domain = v } } if len(others) > 3 { switch v := others[3].(type) { case bool: cookie.Secure = v default: if others[3] != nil { cookie.Secure = true } } } if len(others) > 4 { if v, ok := others[4].(bool); ok && v { cookie.HttpOnly = true } } ctx.Resp.Header().Add("Set-Cookie", cookie.String()) } // GetCookie returns given cookie value from request header. func (ctx *Context) GetCookie(name string) string { cookie, err := ctx.Req.Cookie(name) if err != nil { return "" } val, _ := url.QueryUnescape(cookie.Value) return val } // GetCookieInt returns cookie result in int type. func (ctx *Context) GetCookieInt(name string) int { return com.StrTo(ctx.GetCookie(name)).MustInt() } // GetCookieInt64 returns cookie result in int64 type. func (ctx *Context) GetCookieInt64(name string) int64 { return com.StrTo(ctx.GetCookie(name)).MustInt64() } // GetCookieFloat64 returns cookie result in float64 type. func (ctx *Context) GetCookieFloat64(name string) float64 { v, _ := strconv.ParseFloat(ctx.GetCookie(name), 64) return v } var defaultCookieSecret string // SetDefaultCookieSecret sets global default secure cookie secret. func (m *Macaron) SetDefaultCookieSecret(secret string) { defaultCookieSecret = secret } // SetSecureCookie sets given cookie value to response header with default secret string. func (ctx *Context) SetSecureCookie(name, value string, others ...interface{}) { ctx.SetSuperSecureCookie(defaultCookieSecret, name, value, others...) } // GetSecureCookie returns given cookie value from request header with default secret string. func (ctx *Context) GetSecureCookie(key string) (string, bool) { return ctx.GetSuperSecureCookie(defaultCookieSecret, key) } // SetSuperSecureCookie sets given cookie value to response header with secret string. func (ctx *Context) SetSuperSecureCookie(secret, name, value string, others ...interface{}) { m := md5.Sum([]byte(secret)) secret = hex.EncodeToString(m[:]) text, err := com.AESEncrypt([]byte(secret), []byte(value)) if err != nil { panic("error encrypting cookie: " + err.Error()) } ctx.SetCookie(name, hex.EncodeToString(text), others...) } // GetSuperSecureCookie returns given cookie value from request header with secret string. func (ctx *Context) GetSuperSecureCookie(secret, key string) (string, bool) { val := ctx.GetCookie(key) if val == "" { return "", false } data, err := hex.DecodeString(val) if err != nil { return "", false } m := md5.Sum([]byte(secret)) secret = hex.EncodeToString(m[:]) text, err := com.AESDecrypt([]byte(secret), data) return string(text), err == nil } func (ctx *Context) setRawContentHeader() { ctx.Resp.Header().Set("Content-Description", "Raw content") ctx.Resp.Header().Set("Content-Type", "text/plain") ctx.Resp.Header().Set("Expires", "0") ctx.Resp.Header().Set("Cache-Control", "must-revalidate") ctx.Resp.Header().Set("Pragma", "public") } // ServeContent serves given content to response. func (ctx *Context) ServeContent(name string, r io.ReadSeeker, params ...interface{}) { modtime := time.Now() for _, p := range params { switch v := p.(type) { case time.Time: modtime = v } } ctx.setRawContentHeader() http.ServeContent(ctx.Resp, ctx.Req.Request, name, modtime, r) } // ServeFileContent serves given file as content to response. func (ctx *Context) ServeFileContent(file string, names ...string) { var name string if len(names) > 0 { name = names[0] } else { name = path.Base(file) } f, err := os.Open(file) if err != nil { if Env == PROD { http.Error(ctx.Resp, "Internal Server Error", 500) } else { http.Error(ctx.Resp, err.Error(), 500) } return } defer f.Close() ctx.setRawContentHeader() http.ServeContent(ctx.Resp, ctx.Req.Request, name, time.Now(), f) } // ServeFile serves given file to response. func (ctx *Context) ServeFile(file string, names ...string) { var name string if len(names) > 0 { name = names[0] } else { name = path.Base(file) } ctx.Resp.Header().Set("Content-Description", "File Transfer") ctx.Resp.Header().Set("Content-Type", "application/octet-stream") ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+name) ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary") ctx.Resp.Header().Set("Expires", "0") ctx.Resp.Header().Set("Cache-Control", "must-revalidate") ctx.Resp.Header().Set("Pragma", "public") http.ServeFile(ctx.Resp, ctx.Req.Request, file) } // ChangeStaticPath changes static path from old to new one. func (ctx *Context) ChangeStaticPath(oldPath, newPath string) { if !filepath.IsAbs(oldPath) { oldPath = filepath.Join(Root, oldPath) } dir := statics.Get(oldPath) if dir != nil { statics.Delete(oldPath) if !filepath.IsAbs(newPath) { newPath = filepath.Join(Root, newPath) } *dir = http.Dir(newPath) statics.Set(dir) } } macaron-1/context_test.go 0000664 0000000 0000000 00000025460 12654131704 0015720 0 ustar 00root root 0000000 0000000 // Copyright 2014 The Macaron Authors // // Licensed under the Apache License, Version 2.0 (the "License"): you may // not use this file except in compliance with the License. You may obtain // a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations // under the License. package macaron import ( "bytes" "io/ioutil" "net/http" "net/http/httptest" "net/url" "strings" "testing" "time" "github.com/Unknwon/com" . "github.com/smartystreets/goconvey/convey" ) func Test_Context(t *testing.T) { Convey("Do advanced encapsulation operations", t, func() { m := Classic() m.Use(Renderers(RenderOptions{ Directory: "fixtures/basic", }, "fixtures/basic2")) Convey("Get request body", func() { m.Get("/body1", func(ctx *Context) { data, err := ioutil.ReadAll(ctx.Req.Body().ReadCloser()) So(err, ShouldBeNil) So(string(data), ShouldEqual, "This is my request body") }) m.Get("/body2", func(ctx *Context) { data, err := ctx.Req.Body().Bytes() So(err, ShouldBeNil) So(string(data), ShouldEqual, "This is my request body") }) m.Get("/body3", func(ctx *Context) { data, err := ctx.Req.Body().String() So(err, ShouldBeNil) So(data, ShouldEqual, "This is my request body") }) for i := 1; i <= 3; i++ { resp := httptest.NewRecorder() req, err := http.NewRequest("GET", "/body"+com.ToStr(i), nil) req.Body = ioutil.NopCloser(bytes.NewBufferString("This is my request body")) So(err, ShouldBeNil) m.ServeHTTP(resp, req) } }) Convey("Get remote IP address", func() { m.Get("/remoteaddr", func(ctx *Context) string { return ctx.RemoteAddr() }) resp := httptest.NewRecorder() req, err := http.NewRequest("GET", "/remoteaddr", nil) req.RemoteAddr = "127.0.0.1:3333" So(err, ShouldBeNil) m.ServeHTTP(resp, req) So(resp.Body.String(), ShouldEqual, "127.0.0.1") }) Convey("Render HTML", func() { Convey("Normal HTML", func() { m.Get("/html", func(ctx *Context) { ctx.HTML(304, "hello", "Unknwon") // 304 for logger test. }) resp := httptest.NewRecorder() req, err := http.NewRequest("GET", "/html", nil) So(err, ShouldBeNil) m.ServeHTTP(resp, req) So(resp.Body.String(), ShouldEqual, "