本文整理匯總了Golang中github.com/codegangsta/inject.New函數的典型用法代碼示例。如果您正苦於以下問題:Golang New函數的具體用法?Golang New怎麽用?Golang New使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了New函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: Test_InjectorSetParent
func Test_InjectorSetParent(t *testing.T) {
injector := inject.New()
injector.MapTo("another dep", (*SpecialString)(nil))
injector2 := inject.New()
injector2.SetParent(injector)
expect(t, injector2.Get(inject.InterfaceOf((*SpecialString)(nil))).IsValid(), true)
}
示例2: main
//結論:Apply方法是用於對struct的字段進行注入,參數為指向底層類型為結構體的指針。
//可注入的前提是:字段必須是導出的(也即字段名以大寫字母開頭),並且此字段的tag設置為`inject`
func main() {
s := TestStruct{}
inj := inject.New()
inj.Map("陳一回")
inj.MapTo("男", (*SpecialString)(nil))
inj2 := inject.New()
inj2.Map(20)
inj.SetParent(inj2)
inj.Apply(&s)
fmt.Println("s.Name =", s.Name)
fmt.Println("s.Gender =", s.Gender)
fmt.Println("s.Age =", s.Age)
fmt.Println("s.Nick =", s.Nick)
fmt.Println("s.uid =", s.uid)
}
示例3: MakeHandler
func (ae *App) MakeHandler(handlers ...interface{}) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
child := inject.New()
child.SetParent(ae.Injector)
child.MapTo(w, (*http.ResponseWriter)(nil))
child.Map(r)
handlerLoop:
for _, reqProcessor := range handlers {
result, err := child.Invoke(reqProcessor)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(os.Stderr, "error in url %v: %v\n", r.URL, err)
return
}
if len(result) == 0 {
continue
} else {
valAsInterface := result[0].Interface()
if resp, ok := valAsInterface.(HTTPResponse); ok {
err := resp.Render(w)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintln(os.Stderr, "error: %v", err)
}
if reflect.TypeOf(valAsInterface) != reflect.TypeOf(ChainHttpResponse{}) {
break handlerLoop
}
}
}
}
}
}
示例4: TestInjectImplementors
func TestInjectImplementors(t *testing.T) {
injector := inject.New()
g := &Greeter{"Jeremy"}
injector.Map(g)
expect(t, injector.Get(inject.InterfaceOf((*fmt.Stringer)(nil))).IsValid(), true)
}
示例5: wrap
func wrap(f interface{}) func(*cli.Context) {
return func(ctx *cli.Context) {
if ctx.GlobalBool("debug") {
log.SetOutputLevel(log.Ldebug)
}
sockPath := filepath.Join(GOSUV_HOME, "gosuv.sock")
if err := testConnection("unix", sockPath); err != nil {
log.Fatal(err)
}
conn, err := connect(ctx)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
programClient := pb.NewProgramClient(conn)
gosuvClient := pb.NewGoSuvClient(conn)
inj := inject.New()
inj.Map(programClient)
inj.Map(gosuvClient)
inj.Map(ctx)
inj.Invoke(f)
}
}
示例6: Test_InjectorInvoke
func Test_InjectorInvoke(t *testing.T) {
injector := inject.New()
expect(t, injector == nil, false)
dep := "some dependency"
injector.Map(dep)
dep2 := "another dep"
injector.MapTo(dep2, (*SpecialString)(nil))
dep3 := make(chan *SpecialString)
dep4 := make(chan *SpecialString)
typRecv := reflect.ChanOf(reflect.RecvDir, reflect.TypeOf(dep3).Elem())
typSend := reflect.ChanOf(reflect.SendDir, reflect.TypeOf(dep4).Elem())
injector.Set(typRecv, reflect.ValueOf(dep3))
injector.Set(typSend, reflect.ValueOf(dep4))
_, err := injector.Invoke(func(d1 string, d2 SpecialString, d3 <-chan *SpecialString, d4 chan<- *SpecialString) {
expect(t, d1, dep)
expect(t, d2, dep2)
expect(t, reflect.TypeOf(d3).Elem(), reflect.TypeOf(dep3).Elem())
expect(t, reflect.TypeOf(d4).Elem(), reflect.TypeOf(dep4).Elem())
expect(t, reflect.TypeOf(d3).ChanDir(), reflect.RecvDir)
expect(t, reflect.TypeOf(d4).ChanDir(), reflect.SendDir)
})
expect(t, err, nil)
}
示例7: Injs
func Injs(args ...interface{}) Injector {
inj := inject.New()
for _, v := range args {
inj.Map(v)
}
return inj
}
示例8: JoinBy
// 連接函數 返回error 結束 下一次傳遞
func JoinBy(t interface{}, fs ...interface{}) interface{} {
val := reflect.ValueOf(t)
if val.Kind() != reflect.Func {
return nil
}
for k, v := range fs {
c := toCaller(v)
if c == nil {
return nil
}
fs[k] = c
}
typ := val.Type()
r := reflect.MakeFunc(typ, func(args []reflect.Value) (results []reflect.Value) {
inj := inject.New()
for _, v := range args {
inj.Set(v.Type(), v)
}
inj = SliceFunc(inj, fs)
for i := 0; i != typ.NumOut(); i++ {
results = append(results, inj.Get(typ.Out(i)))
}
return
})
return r.Interface()
}
示例9: Test_Static_Options_Logging
func Test_Static_Options_Logging(t *testing.T) {
response := httptest.NewRecorder()
var buffer bytes.Buffer
m := &Martini{Injector: inject.New(), action: func() {}, logger: log.New(&buffer, "[martini] ", 0)}
m.Map(m.logger)
m.Map(defaultReturnHandler())
opt := StaticOptions{}
m.Use(Static(currentRoot, opt))
req, err := http.NewRequest("GET", "http://localhost:3000/martini.go", nil)
if err != nil {
t.Error(err)
}
m.ServeHTTP(response, req)
expect(t, response.Code, http.StatusOK)
expect(t, buffer.String(), "[martini] [Static] Serving /martini.go\n")
// Now without logging
m.Handlers()
buffer.Reset()
// This should disable logging
opt.SkipLogging = true
m.Use(Static(currentRoot, opt))
m.ServeHTTP(response, req)
expect(t, response.Code, http.StatusOK)
expect(t, buffer.String(), "")
}
示例10: New
// create new helper, this object will be used for globar service for martini middleware
func New() *MartiniHelper {
this := &MartiniHelper{inject.New()}
retHandler := martini.New().Get(reflect.TypeOf(martini.ReturnHandler(nil))).Interface()
// retHandler := martini.defaultReturnHandler()
this.Map(retHandler)
return this
}
示例11: Trigger
func (e *eventManager) Trigger(eventName EventType, data map[string]interface{}) {
e.Lock()
defer e.Unlock()
handlers, ok := e.events[eventName]
wildcardHandlers, wok := e.events[AllEvents]
if !ok && !wok {
return
}
event := Event{eventName, data}
c := inject.New()
c.SetParent(e.injector)
c.Map(event)
if ok {
for _, handler := range handlers {
c.Invoke(handler.Interface())
}
}
if wok {
for _, handler := range wildcardHandlers {
c.Invoke(handler.Interface())
}
}
}
示例12: NewApp
func NewApp() *App {
return &App{
TemplateFuncs: make(map[string]interface{}),
TemplateCache: make(map[string]*template.Template),
CacheTemplates: true,
Injector: inject.New(),
}
}
示例13: createContext
func (m *Martini) createContext(res http.ResponseWriter, req *http.Request) *context {
c := &context{inject.New(), m.handlers, m.action, NewResponseWriter(res), 0}
c.SetParent(m)
c.MapTo(c, (*Context)(nil))
c.MapTo(c.rw, (*http.ResponseWriter)(nil))
c.Map(req)
return c
}
示例14: Test_InjectorGet
func Test_InjectorGet(t *testing.T) {
injector := inject.New()
injector.Map("some dependency")
expect(t, injector.Get(reflect.TypeOf("string")).IsValid(), true)
expect(t, injector.Get(reflect.TypeOf(11)).IsValid(), false)
}
示例15: worker
func (w *WorkerConfig) worker(id string) {
injector := inject.New()
injector.SetParent(w.Injector)
for msg := range w.workQueue {
if msg.die {
break
}
job := msg.job
typ, ok := w.workerMapping[msg.job.Type]
if !ok {
err := UnknownWorkerError{job.Type}
w.scheduleRetry(job, err, true)
continue
}
w.trackJobStart(job, id)
// wrap Perform() in a function so that we can recover from panics
var err error
var worker interface{}
func() {
defer func() {
if r := recover(); r != nil {
err = newPanicError(r)
}
}()
workerVal := reflect.New(typ)
worker = workerVal.Interface()
if err = json.Unmarshal(*job.Args, worker); err != nil {
return
}
injector.Map(job)
if err = injector.Apply(worker); err != nil {
return
}
var res []reflect.Value
res, err = injector.Invoke(workerVal.MethodByName("Perform").Interface())
if err != nil {
return
}
if resErr := res[0].Interface(); resErr != nil && resErr.(error) != nil {
err = resErr.(error)
}
}()
if err != nil {
report := true
if checker, ok := worker.(ReportableErrorChecker); ok {
report = checker.ReportableError(err)
}
w.scheduleRetry(job, err, report)
}
w.trackJobFinish(job, id, err == nil)
}
w.done.Done()
}