Macaron的注入struct

#web服務器html

瀏覽一個網頁就像買啤酒,你給我錢(http請求),我給你啤酒(http返回)
web服務器就充當了營業員的角色
買啤酒從宏觀來看,就2步,一手交錢一手交貨。其實營業員在給你啤酒以前,還作了其餘的事情,好比驗鈔和查看庫存等。而且是有前後順序的,通常是驗鈔經過後,再去查看庫存。
web服務器也同樣,它收到瀏覽器發來的請求後,會按預約設計的順序來作一個一個的function,最後將處理的結果返回給瀏覽器。瀏覽器拿到返回的內容(html源碼),就能夠畫在屏幕上給用戶看了。git

#macaron.Usegithub

Use方法,就是用來註冊一個一個的func的,這些func是全局的,也就是任何http請求過來,會最早調用這些func,以此執行。註冊的順序也就是執行的順序。
Use方法可使用屢次,但每次只能註冊一個func。web

m.Use(func(){
    println(1)
})
m.Use(func(){
    println(2)
})
// 任何http請求過來,會先打印1,再打印2在控制檯上

#macaron.Get瀏覽器

Get方法也是來註冊與上面Use同樣的func的,Get方法註冊的func 會在 Use註冊的func執行完畢後,再依次執行。
Get方法只能使用1次(相同pattern的狀況下),能夠同時註冊1個或n個func,用逗號隔開服務器

m.Get("/",func(){
        println(3)
    },
    func(){
        println(4)
    })
// 若是訪問的是「/」,會再繼續打印3和4在控制檯上

到目前爲止,尚未注入任何東西,因此只能用macaron.Context.net

m := macaron.Classic() 事實上用經典模式已經幫你注入了一些了。先看成沒有注入來看

#開始注入設計

先注入一個Student的structcode

// 這裏是Student的定義,之後再也不說了
type Student struct {
Id   int
Name string
}

func (s *Student) GetName() string {
	return s.Name
}

func (s *Student) Job() {
	fmt.Println("study..")
}

注入的func,這裏的注入,就至關於註冊參數,使用Map的方法來註冊參數htm

ctx.Map("arg2") //註冊string類型的參數爲arg2
ctx.Map(s) //註冊Student類型的參數爲s(也就是小明的那個實例)
// 關於注入,看http://my.oschina.net/u/943306/blog/500237

代碼:

func MidStruct(opt string) macaron.Handler {
    var s *Student
    if opt == "xm" {
        s = &Student{Id: 1, Name: "xiao ming"}
    } else {
        s = &Student{Id: 1, Name: "xiao wang"}
    }
    
    return func(ctx *macaron.Context) {
        ctx.Map(s)  //關鍵語句,用於注入struct
    }
}

執行注入

m.Use(MidStruct("xm")) //執行注入動做

使用struct

// 若是以前注入過,那以後就能夠取到被注入的struct了
    m.Get("/",func(){
        println(3)
    },
    func(){
        println(4)
    },
    func(s *Student){  //由於以前注入過了,因此這裏直接用不會報錯
        s.Job() //打印完上面的4後,會再打印一行study..
    })

這裏的最後一個func,就至關於(http://my.oschina.net/u/943306/blog/500237#OSC_h1_9) 裏的f2

#完整代碼

package main

import (
	"fmt"
	"github.com/Unknwon/macaron"
)

func main() {

	m := macaron.Classic()
	m.Use(MidStruct("xm"))

	m.Get("/", func(ctx *macaron.Context, s *Student) {
		fmt.Println(s.GetName())
		s.Job()
	})

	m.Run()
}

func MidStruct(opt string) macaron.Handler {
	var s *Student
	if opt == "xm" {
		s = &Student{Id: 1, Name: "xiao ming"}
	} else {
		s = &Student{Id: 1, Name: "xiao wang"}
	}

	return func(ctx *macaron.Context) {
		ctx.Map(s)
	}
}

type Student struct {
	Id   int
	Name string
}

func (s *Student) GetName() string {
	return s.Name
}

func (s *Student) Job() {
	fmt.Println("study..")
}
相關文章
相關標籤/搜索