Giter Club home page Giter Club logo

Comments (4)

 avatar commented on August 22, 2024

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.

pcariel avatar pcariel commented on August 22, 2024

Nice, Thank you!

from examples.

 avatar commented on August 22, 2024

@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.

pcariel avatar pcariel commented on August 22, 2024

iris version 7, it's like a great lego !!!

from examples.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.