Last active
August 29, 2015 14:04
-
-
Save omeid/81e17a22618d27a09fd3 to your computer and use it in GitHub Desktop.
Concept: Martini like Go Meta Framework Using Code Generation.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"net/http" | |
"github.com/gorilla/mux" | |
) | |
type testHandler struct { | |
id int | |
name string | |
} | |
func (h *testHandler) Handle(w http.ResponseWriter, r *http.Request, params map[string]string, id int, name string) { | |
param := params["param"] | |
fmt.Fprintf(w, "Hello, %s (%d): param: %s", name, id, param) | |
} | |
func (h *testHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
params := mux.Vars(r) | |
h.Handle(w, r, params, h.id, h.name) | |
} | |
func BuildtestHandler(id int, name string) *testHandler { | |
return &testHandler{id, name} | |
} | |
func main() { | |
rtr := mux.NewRouter() | |
id := 1 | |
name := "first" | |
rtr.Handle("/{param}", BuildtestHandler(id, name)).Methods("GET") | |
http.Handle("/", rtr) | |
log.Println("Listening...") | |
http.ListenAndServe(":3000", nil) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"net/http" | |
) | |
func main() { | |
m := rickey.New() | |
id := 1 | |
name := "first" | |
m.Use(id) | |
m.Use(name) | |
//Handler: test | |
m.Get("/{param}", func(w http.ResponseWriter, r *http.Request, params rickey.Params, id int, name string) { | |
param := params["param"] | |
fmt.Fprintf(w, "Hello, %s (%d): New text: %s", name, id, param) | |
}) | |
m.Run(":3000") | |
} |
As we are using code generation to avoid typing too much, might as well do it all with http.Handlers without even using Gorilla, but undoubtedly there is a lot that can be learned from the Gorilla code base to create a better solution.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The idea here is that the end result should be perfectly human readable and structured based on Go's http.Handler. The middlewares will be just http.Handler's too.