Package macaron is a high productive and modular web framework in Go.

Macaron

GitHub Workflow Status codecov GoDoc Sourcegraph

Macaron Logo

Package macaron is a high productive and modular web framework in Go.

Getting Started

The minimum requirement of Go is 1.6.

To install Macaron:

go get gopkg.in/macaron.v1

The very basic usage of Macaron:

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.
  • 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 to simplify your work:

  • render - Go template engine
  • static - Serves static files
  • gzip - Gzip compression to all responses
  • binding - Request data binding and validation
  • i18n - Internationalization and Localization
  • cache - Cache manager
  • session - Session manager
  • csrf - Generates and validates csrf tokens
  • captcha - Captcha service
  • pongo2 - Pongo2 template engine support
  • sockets - WebSockets channels binding
  • bindata - Embed binary data as static and template files
  • toolbox - Health check, pprof, profile and statistic services
  • oauth2 - OAuth 2.0 backend
  • authz - ACL/RBAC/ABAC authorization based on Casbin
  • switcher - Multiple-site support
  • method - HTTP method override
  • permissions2 - Cookies, users and permissions
  • renders - Beego-like render engine(Macaron has built-in template engine, this is another option)
  • piwik - Server-side piwik analytics

Use Cases

  • Gogs: A painless self-hosted Git Service
  • Grafana: The open platform for beautiful analytics and monitoring
  • Peach: A modern web documentation server
  • Go Walker: Go online API documentation
  • Critical Stack Intel: A 100% free intel marketplace from Critical Stack, Inc.

Getting Help

Credits

License

This project is under the Apache License, Version 2.0. See the LICENSE file for the full license text.

Owner
Macaron
A high productive and modular web framework in Go.
Macaron
Comments
  • Generators

    Generators

    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.

  • url重定向漏洞

    url重定向漏洞

    测试代码:

    package main
    
    import (
    	"gopkg.in/macaron.v1"
    )
    
    func main() {
    	m := macaron.Classic()
    	m.Use(macaron.Renderer())
    
    	m.Get("/", LoginIndex)
    	m.Run()
    }
    
    func LoginIndex(ctx *macaron.Context) {
    	ctx.Write([]byte("fdasfas"))
    
    }
    

    构造以下的请求会跳转到指向的URL,可以用来做钓鱼攻击(FireFox和Safari上有效,chrome没成功)。 curl -v http://127.0.0.1:4000//www.baidu.com/%2e%2e

  • Add Support to autocert as default HTTPS

    Add Support to autocert as default HTTPS

    Nowadays every webserver must run over HTTPS (TLS). Golang Autocert automatically generates and manages Let's Encrypt certs. The method below is a suggestion to include to Macaton struct to be very easy to all Go-Macaron users run their web applications over HTTPS:

    // RunWithAutoCert the http server with Let's Encrypt Cert automatically generated. Listening 443 by default.
    func (m *Macaron) RunWithAutoCert() {
    	host, port := GetDefaultListenInfo()
    	port = 443
    	addr := host + ":" + com.ToStr(port)
    	logger := m.GetVal(reflect.TypeOf(m.logger)).Interface().(*log.Logger)
    	server := &http.Server{
    		Addr:    addr,
    		Handler: m,
    	}
    	certManager := autocert.Manager{
    		Prompt: autocert.AcceptTOS,
    		Cache:  autocert.DirCache("certs"),
    	}
    	server.TLSConfig = &tls.Config{
    		GetCertificate: certManager.GetCertificate,
    	}
    	logger.Printf("listening HTTPS on %s (%s)\n", addr, safeEnv())
    	logger.Fatalln(server.ListenAndServeTLS("", ""))
    }
    
  • host设置和电脑不同

    host设置和电脑不同

    我的电脑的ip是:192.168.1.116 运行

    m.run()
    

    终端显示:

    [Macaron] listening on linux-hiad:4000 (development)
    [Macaron] listen tcp: lookup linux-hiad on 192.168.1.1:53: no such host
    exit status 1
    
    
  • [POC] Add bindata support for static files and templates.

    [POC] Add bindata support for static files and templates.

    This is a POC and not well implemented but I wanted to start a discussion on adding this type of feature into core Macaron as an option for static/render middleware.

    I have been using bindata (https://github.com/jteeuwen/go-bindata) to pack my templates and public dir so I can simply ship one binary without additional files.

    Usage:

    I just jump into both public and templates and run go-bindata -o ../data/public/public.go -pkg "public" respectively. Then I import and add BinData: to each middleware. Pretty simple concept.

        m.Use(macaron.Static(
            path.Join(setting.StaticRootPath, "public"),
            macaron.StaticOptions{
                SkipLogging: false,
                BinData:     public.BinData(),
            },
        ))
    
        m.Use(macaron.Renderer(macaron.RenderOptions{
            Directory:  path.Join(setting.StaticRootPath, "templates"),
            Funcs:      []template.FuncMap{base.TemplateFuncs},
            IndentJSON: macaron.Env != macaron.PROD,
            BinData:    templates.BinData(),
        }))
    

    Anyway, just wanted to get a discussion on the concept and see if we could get something like this into core.

  • sockets中间件注册后,影响正常路由

    sockets中间件注册后,影响正常路由

    `

    m := macaron.Classic()
    m.Use(sockets.Messages())
        type Message struct {
    Id   int
    Name string
        }
    m.Use(sockets.JSON(Message{}))
    m.Get("/a", func() {
        log.Println("hello")
    })
    m.Run()
    

    ` 访问http://127.0.0.1:4000/a 提示Origin not allowed,是哪里的错呢?

  • Support HTTP/2 server push

    Support HTTP/2 server push

    about http2 push

    reference HTTP/2 Server Push

    **http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        if pusher, ok := w.(http.Pusher); ok {
            // Push is supported.
            if err := pusher.Push("/app.js", nil); err != nil {
                log.Printf("Failed to push: %v", err)
            }
        }
        // ...
    })**
    

    below is my code

    	m := macaron.New()
    	m.Get("/", func(ctx *macaron.Context) {
    		if push, ok := ctx.Resp.(http.Pusher); ok {
    			log.Println("ok", push)
    		} else {
    			log.Println("no")
    		}
    	})
    	m.Get("/pushTest", func(w http.ResponseWriter, r *http.Request) {
    		if pusher, ok := w.(http.Pusher); ok {
    			log.Println("ok", pusher)
    		} else {
    			log.Println("no")
    		}
    	})
    	log.Panic(http.ListenAndServeTLS(":1234", "server.crt", "server.key", m))
    

    output is always no.Do not support it

  • Setting Response Headers

    Setting Response Headers

    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!

  • Add the Casbin authorization middleware for Macaron

    Add the Casbin authorization middleware for Macaron

    Hi @Unknwon ,

    first thanks for creating such a great project!

    I'm the author of Casbin. It is a Go authorization library that supports access control models like ACL, RBAC, ABAC. See details here: https://github.com/casbin/casbin

    I think Macaron is a very promising web framework, so I have developed an authz middleware for Macaron here: https://github.com/casbin/macaron-authz

    And I want to ask if Macaron-authz can be listed under the README here: https://github.com/go-macaron/macaron#middlewares

    It's better if you can put the entire repo in: https://github.com/go-macaron, and rename it to authz. You can give me rights for this repo so I can maintain it.

    Thanks!

  • 组路由中间件不生效

    组路由中间件不生效

    `

    mm := macaron.Classic()
    mm.Group("/api", func() {
    
    }, func(ctx *macaron.Context) {
        log.Println("中间件")
    })
    mm.Run()
    

    `

    组路由添加的集体中间件好像并没有运行

  • Switch from MD5 to PBKDF2 for AES keys

    Switch from MD5 to PBKDF2 for AES keys

    I'd like to propose that Macaron switch from using MD5 to PBKDF2 for its AES keys https://github.com/go-macaron/macaron/blob/78521e4647ad5dcbabd5734d94582ca2373cbad8/context.go#L443

    I think using MD5 to generate AES keys has some serious flaws. For example, there's a good chance that someone could figure out the AES key in a few seconds if they have a good rainbow table. Also, you can generate MD5 hashes like crazy on consumer-level GPUs (1-5 billion hashes per second easy on a SINGLE GPU that's less than $500) so the key becomes very easy to attack. PBKDF2 is slow (key stretching) and specifically designed for this use case since it's a key derivation function.

    Related to https://github.com/gogits/gogs/issues/4117

  • Macaron causes panic on starting gogs/gitea in an unwritable/unreadable directory

    Macaron causes panic on starting gogs/gitea in an unwritable/unreadable directory

    Hi!

    The init method for macaron causes a panic if the current working directory cannot be read.

    https://github.com/go-macaron/macaron/blob/4df59ae8a50bd2e82ed915ff1ce764b1bb128a9d/macaron.go#L315

    Because this runs on init even if macaron is not going to be started, if it is linked to a binary it will prevent the binary from starting if it is started in a non-readable working directory.

    A workaround is possible but it's not ideal. Is there any way to avoid panicking here?

  • PANIC: reflect: call of reflect.Value.Interface on zero Value

    PANIC: reflect: call of reflect.Value.Interface on zero Value

    [Macaron] PANIC: reflect: call of reflect.Value.Interface on zero Value
    /usr/local/go/src/runtime/panic.go:426 (0x8070a0d)
        gopanic: reflectcall(nil, unsafe.Pointer(d.fn), deferArgs(d), uint32(d.siz), uint32(d.siz))
    /usr/local/go/src/reflect/value.go:913 (0x81a05fa)
        valueInterface: panic(&ValueError{"reflect.Value.Interface", 0})
    /usr/local/go/src/reflect/value.go:908 (0x81a0572)
        Value.Interface: return valueInterface(v, true)
    /home/simon/go/src/github.com/go-macaron/binding/binding.go:333 (0x825ec6b)
        validateField: sliceValue := sliceVal.Interface()
    /home/simon/go/src/github.com/go-macaron/binding/binding.go:320 (0x825e9fe)
        validateStruct: errors = validateField(errors, zero, field, fieldVal, fieldValue)
    /home/simon/go/src/github.com/go-macaron/binding/binding.go:318 (0x825e95a)
        validateStruct: errors = validateStruct(errors, fieldValue)
    /home/simon/go/src/github.com/go-macaron/binding/binding.go:236 (0x8264d23)
        Validate.func1: errors = validateStruct(errors, obj)
    /usr/local/go/src/runtime/asm_386.s:488 (0x80973da)
        call16: CALLFN(·call16, 16)
    /usr/local/go/src/reflect/value.go:435 (0x819ecdb)
        Value.call: call(frametype, fn, args, uint32(frametype.size), uint32(retOffset))
    /usr/local/go/src/reflect/value.go:303 (0x819dcfc)
        Value.Call: return v.call("Call", in)
    /home/simon/go/src/github.com/go-macaron/inject/inject.go:117 (0x81b7fd4)
        (*injector).Invoke: return reflect.ValueOf(f).Call(in), nil
    /home/simon/go/src/github.com/go-macaron/binding/binding.go:633 (0x8263e61)
        validateAndMap: ctx.Invoke(Validate(obj.Interface()))
    /home/simon/go/src/github.com/go-macaron/binding/binding.go:210 (0x82649ed)
        Json.func1: validateAndMap(jsonStruct, ctx, errors, ifacePtr...)
    /usr/local/go/src/runtime/asm_386.s:488 (0x80973da)
        call16: CALLFN(·call16, 16)
    /usr/local/go/src/reflect/value.go:435 (0x819ecdb)
        Value.call: call(frametype, fn, args, uint32(frametype.size), uint32(retOffset))
    /usr/local/go/src/reflect/value.go:303 (0x819dcfc)
        Value.Call: return v.call("Call", in)
    /home/simon/go/src/github.com/go-macaron/inject/inject.go:117 (0x81b7fd4)
        (*injector).Invoke: return reflect.ValueOf(f).Call(in), nil
    /home/simon/go/src/gopkg.in/macaron.v1/context.go:113 (0x809bd54)
        (*Context).run: vals, err := c.Invoke(c.handler())
    /home/simon/go/src/gopkg.in/macaron.v1/context.go:104 (0x809bc68)
        (*Context).Next: c.run()
    /home/simon/go/src/gopkg.in/macaron.v1/recovery.go:161 (0x80ada5b)
        Recovery.func1: c.Next()
    /usr/local/go/src/runtime/asm_386.s:488 (0x80973da)
        call16: CALLFN(·call16, 16)
    /usr/local/go/src/reflect/value.go:435 (0x819ecdb)
        Value.call: call(frametype, fn, args, uint32(frametype.size), uint32(retOffset))
    /usr/local/go/src/reflect/value.go:303 (0x819dcfc)
        Value.Call: return v.call("Call", in)
    /home/simon/go/src/github.com/go-macaron/inject/inject.go:117 (0x81b7fd4)
        (*injector).Invoke: return reflect.ValueOf(f).Call(in), nil
    /home/simon/go/src/gopkg.in/macaron.v1/context.go:113 (0x809bd54)
        (*Context).run: vals, err := c.Invoke(c.handler())
    /home/simon/go/src/gopkg.in/macaron.v1/context.go:104 (0x809bc68)
        (*Context).Next: c.run()
    /home/simon/go/src/gopkg.in/macaron.v1/logger.go:40 (0x80aca1e)
        Logger.func1: ctx.Next()
    /usr/local/go/src/runtime/asm_386.s:488 (0x80973da)
        call16: CALLFN(·call16, 16)
    /usr/local/go/src/reflect/value.go:435 (0x819ecdb)
        Value.call: call(frametype, fn, args, uint32(frametype.size), uint32(retOffset))
    /usr/local/go/src/reflect/value.go:303 (0x819dcfc)
        Value.Call: return v.call("Call", in)
    /home/simon/go/src/github.com/go-macaron/inject/inject.go:117 (0x81b7fd4)
        (*injector).Invoke: return reflect.ValueOf(f).Call(in), nil
    /home/simon/go/src/gopkg.in/macaron.v1/context.go:113 (0x809bd54)
        (*Context).run: vals, err := c.Invoke(c.handler())
    /home/simon/go/src/gopkg.in/macaron.v1/router.go:184 (0x80aef02)
        (*Router).Handle.func1: c.run()
    /home/simon/go/src/gopkg.in/macaron.v1/router.go:286 (0x80a75bd)
        (*Router).ServeHTTP: h(rw, req, p)
    /home/simon/go/src/gopkg.in/macaron.v1/macaron.go:177 (0x80a041f)
        (*Macaron).ServeHTTP: m.Router.ServeHTTP(rw, req)
    /usr/local/go/src/net/http/server.go:2081 (0x816a256)
        serverHandler.ServeHTTP: handler.ServeHTTP(rw, req)
    /usr/local/go/src/net/http/server.go:1472 (0x81676a8)
        (*conn).serve: serverHandler{c.server}.ServeHTTP(w, w.req)
    /usr/local/go/src/runtime/asm_386.s:1585 (0x8099211)
        goexit: BYTE    $0x90   // NOP
    
  • Swagger support

    Swagger support

    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.

An opinionated productive web framework that helps scaling business easier.
An opinionated productive web framework that helps scaling business easier.

appy An opinionated productive web framework that helps scaling business easier, i.e. focus on monolith first, only move to microservices with GRPC la

Nov 4, 2022
GoFrame is a modular, powerful, high-performance and enterprise-class application development framework of Golang.
GoFrame is a modular, powerful, high-performance and enterprise-class application development framework of Golang.

GoFrame English | 简体中文 GoFrame is a modular, powerful, high-performance and enterprise-class application development framework of Golang. If you're a

Jan 2, 2023
Mango is a modular web-application framework for Go, inspired by Rack, and PEP333.

Mango Mango is a modular web-application framework for Go, inspired by Rack and PEP333. Note: Not actively maintained. Overview Mango is most of all a

Nov 17, 2022
A fantastic modular Go web framework boiled with black magic.
A fantastic modular Go web framework boiled with black magic.

A fantastic modular Go web framework boiled with black magic. Getting started The minimum requirement of Go is 1.16. To install Flamego: go get github

Dec 25, 2022
Modular C2 framework aiming to ease post exploitation for red teamers.

test.mp4 testvideo.mp4 Usage: Inside the command server you can reference beacons using either their list id or their unique id. For example if the ou

Dec 17, 2022
Flamingo Framework and Core Library. Flamingo is a go based framework for pluggable web projects. It is used to build scalable and maintainable (web)applications.
Flamingo Framework and Core Library. Flamingo is a go based framework for pluggable web projects. It is used to build scalable and maintainable (web)applications.

Flamingo Framework Flamingo is a web framework based on Go. It is designed to build pluggable and maintainable web projects. It is production ready, f

Jan 5, 2023
Golanger Web Framework is a lightweight framework for writing web applications in Go.

/* Copyright 2013 Golanger.com. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except

Nov 14, 2022
The jin is a simplified version of the gin web framework that can help you quickly understand the core principles of a web framework.

jin About The jin is a simplified version of the gin web framework that can help you quickly understand the core principles of a web framework. If thi

Jul 14, 2022
hiboot is a high performance web and cli application framework with dependency injection support

Hiboot - web/cli application framework About Hiboot is a cloud native web and cli application framework written in Go. Hiboot is not trying to reinven

Nov 20, 2022
Dragon 🐲 🐲 🐲 is an enterprise high performance web framework with Go for the feature and comfortable develop.

Dragon start dragon ab performance Dragon ?? ?? ?? is a lightweight high performance web framework with Go for the feature and comfortable develop. 中文

Sep 14, 2022
Dragon 🐲 🐲 🐲 is a lightweight high performance web framework with Go for the feature and comfortable develop.

Dragon project new link start dragon ab performance Dragon ?? ?? ?? is a lightweight high performance web framework with Go for the feature and comfor

Sep 6, 2022
beego is an open-source, high-performance web framework for the Go programming language.
beego is an open-source, high-performance web framework for the Go programming language.

Beego Beego is used for rapid development of enterprise application in Go, including RESTful APIs, web apps and backend services. It is inspired by To

Jan 1, 2023
High performance, minimalist Go web framework
High performance, minimalist Go web framework

Supported Go versions As of version 4.0.0, Echo is available as a Go module. Therefore a Go version capable of understanding /vN suffixed imports is r

Jan 2, 2023
Gearbox :gear: is a web framework written in Go with a focus on high performance
Gearbox :gear: is a web framework written in Go with a focus on high performance

gearbox ⚙️ is a web framework for building micro services written in Go with a focus on high performance. It's built on fasthttp which is up to 10x fa

Jan 3, 2023
A high productivity, full-stack web framework for the Go language.

Revel Framework A high productivity, full-stack web framework for the Go language. Current Version: 1.0.0 (2020-07-11) Supports go.mod package managem

Jan 7, 2023
Goal is a toolkit for high productivity web development in Go language in the spirit of Revel Framework that is built around the concept of code generation.

Goal Goal is a set of tools for high productivity web development in Go language. Goal, being mostly inspired by Revel Framework and its discussions,

Sep 27, 2021
A high level web-framework for Go

go-start is a high level web-framework for Go, like Django for Python or Rails for Ruby. Installation: go get github.com/ungerik/go-start Documentatio

Dec 24, 2022
Gearbox :gear: is a web framework written in Go with a focus on high performance
Gearbox :gear: is a web framework written in Go with a focus on high performance

gearbox ⚙️ is a web framework for building micro services written in Go with a focus on high performance. It's built on fasthttp which is up to 10x fa

Dec 29, 2022