107 lines
2.2 KiB
Markdown
107 lines
2.2 KiB
Markdown
# Server Events
|
|
|
|
## How To
|
|
|
|
In this Example i use the generic-di package to Inject a Service into a Event.
|
|
first you have to create some Event Handler:
|
|
|
|
services/external_service.go
|
|
|
|
```go
|
|
package services
|
|
|
|
import (
|
|
di "git.apihub24.de/admin/generic-di"
|
|
)
|
|
|
|
func init() {
|
|
di.Injectable(newExternalService)
|
|
}
|
|
|
|
// this Service is only a Example to show how to use a real world authentication service!
|
|
type IExternalService interface {
|
|
CheckLogin(string, string) bool
|
|
}
|
|
|
|
type externalService struct {}
|
|
|
|
func newExternalService() IExternalService {
|
|
return &externalService{}
|
|
}
|
|
|
|
func (service *externalService) CheckLogin(name, password string) bool {
|
|
return len(name) > 0 && len(password) > 0
|
|
}
|
|
```
|
|
|
|
events/login_event.go
|
|
|
|
```go
|
|
package events
|
|
|
|
import (
|
|
|
|
di "git.apihub24.de/admin/generic-di"
|
|
)
|
|
|
|
// a Struct of the Login success EventData
|
|
type UserLogin struct {
|
|
UserName string `json:"userName"`
|
|
}
|
|
|
|
// a Struct of the Login EventData
|
|
type LoginData struct {
|
|
Login string `json:"login"`
|
|
Password string `json:"password"`
|
|
}
|
|
|
|
type LoginEvent struct {
|
|
someExternalService services.IExternalService
|
|
}
|
|
|
|
func NewLoginEvent() *LoginEvent {
|
|
return &LoginEvent{
|
|
someExternalService: di.Inject[services.IExternalService]()
|
|
}
|
|
}
|
|
|
|
// implement a Method to get the EventName String
|
|
func (event *LoginEvent) GetEventName() string {
|
|
return "login"
|
|
}
|
|
|
|
// implement a Method to check if the Event can Execute
|
|
func (event *LoginEvent) CanExecute(ctx *serverevents.Context) bool {
|
|
return true
|
|
}
|
|
|
|
// implement a Method to send non Authorized Response
|
|
func (event *UserLoginEvent) SendNotAuthorizedResponse(ctx *serverevents.Context) {
|
|
}
|
|
|
|
// implement a Method to Handle a Event
|
|
func (event *UserLoginEvent) Handle(ctx *serverevents.Context) {
|
|
data, dataParseErr := serverevents.GetEventData[LoginData](ctx)
|
|
if dataParseErr != nil {
|
|
ctx.Send(http.StatusInternalServerError, "text/plain", []byte(dataParseErr.Error()))
|
|
return
|
|
}
|
|
|
|
if !event.someExternalService.CheckLogin(data.Login, data.Password) {
|
|
// send a new Event to the Client
|
|
ctx.Emit(serverevents.Event{
|
|
Type: "login fail",
|
|
Data: "login fails!",
|
|
})
|
|
return
|
|
}
|
|
|
|
ctx.Emit(serverevents.Event{
|
|
Type: "login success",
|
|
Data: UserLogin{
|
|
UserName: "some Username",
|
|
},
|
|
})
|
|
}
|
|
```
|