linzhengen / tech-notes

My tech notes write in github issues🧲
1 stars 0 forks source link

[20201209] google/wire はいい感じにDIソースコード生成してくれた #52

Open linzhengen opened 3 years ago

linzhengen commented 3 years ago

https://github.com/google/wire

依存関係のロジック hoge.go

// Message is what greeters will use to greet guests.
type Message string

// NewMessage creates a default Message.
func NewMessage(phrase string) Message {
    return Message(phrase)
}

// NewGreeter initializes a Greeter. If the current epoch time is an even
// number, NewGreeter will create a grumpy Greeter.
func NewGreeter(m Message) Greeter {
    var grumpy bool
    if time.Now().Unix()%2 == 0 {
        grumpy = true
    }
    return Greeter{Message: m, Grumpy: grumpy}
}

// Greeter is the type charged with greeting guests.
type Greeter struct {
    Grumpy  bool
    Message Message
}

// Greet produces a greeting for guests.
func (g Greeter) Greet() Message {
    if g.Grumpy {
        return Message("Go away!")
    }
    return g.Message
}

// NewEvent creates an event with the specified greeter.
func NewEvent(g Greeter) (Event, error) {
    if g.Grumpy {
        return Event{}, errors.New("could not create event: event greeter is grumpy")
    }
    return Event{Greeter: g}, nil
}

// Event is a gathering with greeters.
type Event struct {
    Greeter Greeter
}

// Start ensures the event starts with greeting all guests.
func (e Event) Start() {
    msg := e.Greeter.Greet()
    fmt.Println(msg)
}

wire.go

// ビルドタグで除外
//+build wireinject

// The build tag makes sure the stub is not built in the final build.
package main

import "github.com/google/wire"

// InitializeEvent creates an Event. It will error if the Event is staffed with
// a grumpy greeter.
func InitializeEvent(phrase string) (Event, error) {
    wire.Build(NewEvent, NewGreeter, NewMessage)
    return Event{}, nil
}

wire ./のコマンドで下記のソースコードが生成された、賢い!!!

wire_gen.go

// Code generated by Wire. DO NOT EDIT.

//go:generate wire
//+build !wireinject

package main

// Injectors from wire.go:

func InitializeEvent(phrase string) (Event, error) {
    message := NewMessage(phrase)
    greeter := NewGreeter(message)
    event, err := NewEvent(greeter)
    if err != nil {
        return Event{}, err
    }
    return event, nil
}