Comments (4)
Hello you can already create a custom context but you will also need a handler wrapper because Go doesn't supports generic as you already know, so the system doesn't know that you 'changed' the type from *Context to *MyContext, the c.map
in your example is useless because Go simple doesn't supports these things. Code means 10000 words:
mycontext.go
package main
import (
"sync"
"gopkg.in/kataras/iris.v6"
)
// We use sync.Pool to reduce the memory allocations and make our context creator/or get faster
// Read its source code, it's good to know how it works: https://golang.org/src/sync/pool.go
var contextPool sync.Pool
func acquireContext(ctx *iris.Context) *MyContext {
/*
Note:
We could just set the contextPool.New field without the need of the acquire and release functions.
I choose this method because it gives us more control what to initialize(request-scope) and what not to,
in this example we don't have any complicated logic, so it doesn't really matters.
Anyway, I am recommending you to use this 'manual' way to work with your sync.Pools.
*/
v := contextPool.Get()
var myContext *MyContext
if v == nil {
myContext = &MyContext{}
} else {
myContext = v.(*MyContext)
}
myContext.Reset(ctx)
// pass any other useful variables to the Reset,
// you can also wrap this functionality to a struct like MyApp witch will contain all fields that the context needs
return myContext
}
func releaseContext(m *MyContext) {
contextPool.Put(m)
}
// MyHandler is my custom handler wihch implements the iris.Handler too
type MyHandler func(*MyContext)
// Serve is the func which makes MyHandler a valid iris Handler
// iris.Handler is just an interface contains one func of the form: Serve(*iris.Context)
// so any iteral contains Serve(*iris.Context) is a valid iris Handler
func (h MyHandler) Serve(ctx *iris.Context) {
myContext := acquireContext(ctx) // get the context from the pool
h(myContext)
releaseContext(myContext) // release the context as soon the handler finished its job
}
// MyHandlerFunc does the same thing as MyHandler.Serve but instead of returns an iris.Handler
// it returns an iris.HandlerFunc, which also implements the iris.Handler but it's used
// in the most Iris' methods (iris.Get/Post/Put/...) while iris.Handler is used inside iris.Handle(...)
// both methods are valid and equal.
func MyHandlerFunc(h MyHandler) iris.HandlerFunc {
return func(ctx *iris.Context) {
myContext := acquireContext(ctx) // get the context from the pool
h(myContext)
releaseContext(myContext) // release the context as soon the handler finished its job
}
}
// MyContext my custom context contains a request-scope instance of the framework's Context
// and custom functions
type MyContext struct {
// obviously, here is the framework's built'n Context, we wanna need its methods to implement our own or extend the existing functionality
*iris.Context
// =====================================
// any custom request-scope fields here
// =====================================
// this exists for the shake of the example,
// you can set any client-specific field here and pass them via .Reset func
// db Database
}
// Reset resets the context's values, receives any 'objects' that used inside the request-scope context
func (m *MyContext) Reset(ctx *iris.Context) {
m.Context = ctx
// m.db = db
// init/set your other request-scoped context's fields here
}
// =========================
// any custom functions here
// =========================
// Hello prints the rich hello message to the client
func (m *MyContext) Hello() {
m.HTML(iris.StatusOK, "<h1> Hello from my custom func Hello from my custom context called from my custom Handler!</h1>")
}
main.go
package main
import (
"gopkg.in/kataras/iris.v6"
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
)
// set the route(s) and starts the server
func main() {
app := iris.New()
app.Adapt(iris.DevLogger())
app.Adapt(httprouter.New())
// wrap our function-handler to MyHandler type, which is a valid net/http Handler because it implements the net/http.Handler
app.Handle(iris.MethodGet, "/", MyHandler(index))
// or use our custom func to wrap and return an iris.HandlerFunc which also implements the iris.Handler but it's just a func
// both methods are valid and equal.
//app.Get("/", MyHandlerFunc(index))
//starts the server which listening on port 8080, open your browser at location: localhost:8080
app.Listen(":8080")
}
// our custom Handler using our custom MyContext
func index(ctx *MyContext) {
ctx.Hello() // call a custom method lives inside our custom MyContext
}
Do you liked this ? :)
from examples.
Nice, Thank you!
from examples.
@pcariel You're welcome, now you have a second option too: https://github.com/iris-contrib/examples/tree/master/custom-context/method-overriding :)
from examples.
iris version 7, it's like a great lego !!!
from examples.
Related Issues (20)
- [Feature Request] Support slog logger handler
- read form example cannot run HOT 1
- Gzip doesn't work HOT 2
- How to print Session value in Template HOT 1
- Flash Session [ Help Needed ] HOT 1
- get with params HOT 2
- how to read data from client like JMeter HOT 4
- why static file can't be packaged HOT 5
- Can we use mvc service in another service? HOT 3
- How can I get test coverage? HOT 1
- "WithoutVersionChecker" is undefined! HOT 2
- "Hello, webAssembly" link in the table of contents is broken HOT 1
- Error with ctx.URLParams()
- write tcp [::1]:8099->[::1]:64820: wsasend: An established connection was aborted by the software in your host machine.
- WebSocket to REST handlers Adapter
- /create and /decode has no function at the example "Glimpse" HOT 1
- html/template: "movie/index.html" is undefined HOT 1
- Potential import collision: import path should be "go.etcd.io/bbolt", not "github.com/etcd-io/bbolt" HOT 4
- httpexpect doesn't work
- How do I set up a header? HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from examples.