// Valid checks Config data
func (c *Config) Valid() Error {
// Check mapping.hosts
for _, raw := range c.Mapping.Hosts {
if validIP := utils.ValidIP4(raw.IPAddress); !validIP {
err := new(InvalidIPError)
return err
}
}
return nil
}
// Error represents errors in config
type Error interface {
Error() string
}
// InvalidIPError raises when invalid ip provided
type InvalidIPError struct {
HostRaw HostRaw
}
func (e *InvalidIPError) Error() string {
return fmt.Sprintf("You specified invalid IP: %v", e.HostRaw)
}
How I can create instance of InvalidIPError with new keyword and values to send it to return in one line?
For example something like this return new(InvalidIPError{HostRaw: raw})
return &InvalidIPError{HostRaw: raw}
Related
I am trying to do dependency injection in golang with applying dependency inversion principle, so I have the following service
package account
import (
types "zaClouds/modules/account/domain/types"
"zaClouds/modules/shared"
)
type IPlanDomainService interface {
GetUsagePlanById(string) *shared.Result[types.UsagePlan]
}
type PlanDomainService struct {
usagePlanService types.IUsagePlanService
}
func (planDomainService *PlanDomainService) GetUsagePlanById(id string) *shared.Result[types.UsagePlan] {
result := &shared.Result[types.UsagePlan]{}
usagePlanResult := planDomainService.usagePlanService.GetPlanById(id)
if usagePlanResult.Err != nil {
result.Err = usagePlanResult.Err
return result
}
result.Data = usagePlanResult.Data
return result
}
func PlanDomainServiceFactory(usagePlanService types.IUsagePlanService) IPlanDomainService {
return &PlanDomainService{usagePlanService: usagePlanService}
}
as you can see, it accepts another service with type IUsagePlanService
and here is the interface for it
package account
import (
"zaClouds/modules/shared"
"github.com/shopspring/decimal"
)
type UsagePlan struct {
ID string
Title string
Description interface{}
PlanID string
Price decimal.Decimal
Duration int
Features map[string]map[string]string
}
type IUsagePlanService interface {
GetPlanById(string) *shared.Result[UsagePlan]
}
and here is the way I am injecting this service to domain service
func DiInit(usagePlanService interface{}) domainServices.IPlanDomainService {
domainServices.PlanDomainServiceFactory(types.IUsagePlanService(usagePlanService))
return domainServices.PlanDomainServiceFactory(usagePlanService.(types.IUsagePlanService))
}
as you can see, I am trying to do a type assertion but it doesn't work, and gives me the following error:
panic: interface conversion: *usagePlan.UsagePlanRepository is not account.IUsagePlanService: missing method GetPlanById
Edit
Here is the actual implementation for usagePlanService
type IUsagePlanRepository interface {
createClient(string) *http.Request
GetPlanById(string) *shared.Result[usagePlanRepoModels.UsagePlan]
}
type UsagePlanRepository struct {
plansEndpoint string
httpClient *http.Client
}
func (r *UsagePlanRepository) GetPlanById(id string) *shared.Result[usagePlanRepoModels.UsagePlan] {
result := &shared.Result[usagePlanRepoModels.UsagePlan]{}
req := r.createClient(id)
resp, err := r.httpClient.Do(req)
if err != nil {
log.Println("failed to load plan details \n[ERROR]", err)
result.Err = err
return result
}
defer func() {
bodyError := resp.Body.Close()
if bodyError != nil {
result.Err = bodyError
}
}()
if result.Err != nil {
return result
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
utils.Logger.Error("failed to load plan details \n[ERROR]", err, nil)
result.Err = err
return result
}
if resp.StatusCode >= 400 {
result.Err = errors.New(string(body))
utils.Logger.Info("getPlanById", string(body))
}
getUsagePlanResponse, foundError := usagePlanRepoModels.CreateGetUsagePlanResponse(body)
if foundError != nil {
result.Err = foundError
return result
}
result.Data = *getUsagePlanResponse
return result
}
When using an interface, you need to define all functions that you will use with the same name and signature as the implementation.
The error message you got indicates that the implementation and the interface are different.
The implementation is not shown in your question, but you defined the function for your interface like this: GetPlanById(string) *shared.Result[UsagePlan]. Any deviation from it will result in error. One common mistake is with the pointers. Adding or removing the * to the return type will incur in error if it differs from the original.
Edit:
Your interface should look like this:
type IUsagePlanService interface {
GetPlanById(id string) *shared.Result[usagePlanRepoModels.UsagePlan]
}
If your function is returning a private type, and you can change that, you should. If you cant change it, than you should create a function that wraps the function you are trying to abstract with the interface.
I'm trying to unmarshal the following YAML data into Go structures.
The data is the in the following format:
fetchers:
- type: "aws"
config:
omega: "lul"
- type: "kubernetes"
config:
foo: "bar"
Based of the type field, I want to determine wether to unmarshal the config field into awsConfig or kubernetesConfig struct.
My current code looks like this (using "gopkg.in/yaml.v2"):
type kubernetesConfig struct {
foo string `yaml:"foo"`
}
type awsConfig struct {
omega string `yaml:"omega"`
}
var c struct {
Fetchers []struct {
Type string `yaml:"type"`
Config interface{} `yaml:"config"`
} `yaml:"fetchers"`
}
err := yaml.Unmarshal(data, &c)
if err != nil {
log.Fatal(err)
}
for _, val := range c.Fetchers {
switch val.Type {
case "kubernetes":
conf := val.Config.(kubernetesConfig)
fmt.Println(conf.foo)
case "aws":
conf := val.Config.(awsConfig)
fmt.Println(conf.omega)
default:
log.Fatalf("No matching type, was type %v", val.Type)
}
}
Code in playground: https://go.dev/play/p/klxOoHMCtnG
Currently it gets unmarshalled as map[interface {}]interface {}, which can't be converted to one of the structs above.
Error:
panic: interface conversion: interface {} is map[interface {}]interface {}, not main.awsConfig \
Do I have to implemented the Unmarshaler Interface of the YAML package with a custom UnmarshalYAML function to get this done?
Found the solution by implementing Unmarshaler Interface:
type Fetcher struct {
Type string `yaml:"type"`
Config interface{} `yaml:"config"`
}
// Interface compliance
var _ yaml.Unmarshaler = &Fetcher{}
func (f *Fetcher) UnmarshalYAML(unmarshal func(interface{}) error) error {
var t struct {
Type string `yaml:"type"`
}
err := unmarshal(&t)
if err != nil {
return err
}
f.Type = t.Type
switch t.Type {
case "kubernetes":
var c struct {
Config kubernetesConfig `yaml:"config"`
}
err := unmarshal(&c)
if err != nil {
return err
}
f.Config = c.Config
case "aws":
var c struct {
Config awsConfig `yaml:"config"`
}
err := unmarshal(&c)
if err != nil {
return err
}
f.Config = c.Config
}
return nil
}
This type of task - where you want to delay the unmarshaling - is very similar to how json.RawMessage works with examples like this.
The yaml package does not have a similar mechanism for RawMessage - but this technique can easily be replicated as outlined here:
type RawMessage struct {
unmarshal func(interface{}) error
}
func (msg *RawMessage) UnmarshalYAML(unmarshal func(interface{}) error) error {
msg.unmarshal = unmarshal
return nil
}
// call this method later - when we know what concrete type to use
func (msg *RawMessage) Unmarshal(v interace{}) error {
return msg.unmarshal(v)
}
So to leverage this in your case:
var fs struct {
Configs []struct {
Type string `yaml:"type"`
Config RawMessage `yaml:"config"` // delay unmarshaling
} `yaml:"fetchers"`
}
err = yaml.Unmarshal([]byte(data), &fs)
if err != nil {
return
}
and based on the config "Type" (aws or kubernetes), you can finally unmarshal the RawMessage into the correct concrete type:
aws := awsConfig{} // concrete type
err = c.Config.Unmarshal(&aws)
or:
k8s := kubernetesConfig{} // concrete type
err = c.Config.Unmarshal(&k8s)
Working example here: https://go.dev/play/p/wsykOXNWk3H
I'm trying to build a method that, using the Kubernetes client-go library, fetches and returns the actual Resources for a given *metav1.OwnerReference. I have this:
func fetchResource(ref *metav1.OwnerReference, options *RequestOptions) (*metav1.ObjectMeta, error) {
switch ref.Kind {
case "ReplicaSet":
return options.Clientset.AppsV1().ReplicaSets(options.Namespace).Get(options.Context, ref.Name, metav1.GetOptions{})
case "Deployment":
return options.Clientset.AppsV1().Deployments(options.Namespace).Get(options.Context, ref.Name, metav1.GetOptions{})
case "Job":
fallthrough
// more stuff...
default:
return nil, nil
}
}
This code does not compile because:
cannot use options.Clientset.AppsV1().ReplicaSets(options.Namespace).Get(options.Context, ref.Name, (metav1.GetOptions literal)) (value of type *"k8s.io/api/apps/v1".ReplicaSet) as *"k8s.io/apimachinery/pkg/apis/meta/v1".ObjectMeta value in return statement
My guess was that since the documentation says that basically all resources embedd the metav1.ObjectMeta, I could use it as a return type.
I tried creating and returning an interface instead, but realized I can't implement it for types outside my package:
type K8sResource interface {
Name() string
Kind() string
OwnerReferences() []metav1.OwnerReference
}
func (pod *corev1.Pod) Name() string {
return pod.Name
}
func (pod *corev1.Pod) Kind() string {
return pod.Kind
}
func (pod *corev1.Pod) OwnerReferences() []metav1.OwnerReference {
return pod.OwnerReferences
}
This code does not compile because:
invalid receiver *"k8s.io/api/core/v1".Pod (type not defined in this package)
What would be the idiomatic and correct solution here?
If you want to return the imported types as an interface that they don't already implement, you can wrap them in types that do implement it.
For example:
type K8sResource interface {
Name() string
Kind() string
OwnerReferences() []metav1.OwnerReference
}
type replicaSet struct{ *v1.ReplicaSet }
func (s replicaSet) Name() string {
return s.ReplicaSet.Name
}
func (s replicaSet) Kind() string {
return s.ReplicaSet.Kind
}
func (s replicaSet) OwnerReferences() []metav1.OwnerReference {
return s.ReplicaSet.OwnerReferences
}
func fetchResource(ref *metav1.OwnerReference, options *RequestOptions) (K8sResource, error) {
switch ref.Kind {
case "ReplicaSet":
res, err := options.Clientset.AppsV1().ReplicaSets(options.Namespace).Get(options.Context, ref.Name, metav1.GetOptions{})
if err != nil {
return nil, err
}
return replicaSet{res}, nil // wrap it up
case "Pod":
res, err := options.Clientset.AppsV1().Pods(options.Namespace).Get(options.Context, ref.Name, metav1.GetOptions{})
if err != nil {
return nil, err
}
return pod{res}, nil // wrap it up
case "Job":
fallthrough
// more stuff...
default:
return nil, nil
}
}
I am trying to validate some forms using Beego validation, but it is not working at all: invalid data passes without errors.
This the relevant code, I don't know what is wrong. Can you point me at the mistake?
https://github.com/dionyself/golang-cms/blob/master/models/form.go
package models
import (
"github.com/astaxie/beego"
"github.com/astaxie/beego/validation"
)
type BaseForm struct {
Errors map[string]string
}
func (form *BaseForm) Validate() bool {
valid := validation.Validation{}
b, err := valid.Valid(form)
if err != nil {
beego.Error(err)
}
if !b {
for _, err := range valid.Errors {
form.Errors[err.Key] = err.Message
beego.Debug(err.Key, err.Message)
}
}
return b
}
type RegisterForm struct {
BaseForm
Username string `form:"username" valid:"Required; AlphaNumeric; MinSize(4); MaxSize(300)"`
Password string `form:"password" valid:"Required; MinSize(4); MaxSize(30)"`
PasswordRe string `form:"passwordre" valid:"Required; MinSize(4); MaxSize(30)"`
}
func (form *RegisterForm) Valid(v *validation.Validation) {
// Check if passwords of two times are same.
if form.Password != form.PasswordRe {
v.SetError("PasswordRe", "Passwords did not match")
return
}
}
type ArticleForm struct {
BaseForm
Id int `form:"-"`
Title string `form:"title" valid:"Required;MinSize(4);MaxSize(300)"`
Category int `form:"category"`
Content string `form:"content" valid:"Required; MinSize(50); MaxSize(2000)"`
TopicTags string `form:"topic-tags" valid:"MinSize(4); MaxSize(300)"`
TaggedUsers string `form:"tagged-users" valid:"MinSize(4); MaxSize(300)"`
AllowReviews bool `form:"allow-reviews" valid:"Required"`
AllowComments bool `form:"allow-comments" valid:"Required"`
Errors map[string]string
}
func (form *ArticleForm) Valid(v *validation.Validation) {
if form.Category >= 0 {
v.SetError("Category", "Invalid category")
return
}
}
Some documentation:
http://beego.me/docs/mvc/controller/validation.md
This is the code that parses the form:
func (this *ArticleController) Post() {
form := models.ArticleForm{}
Art := new(models.Article)
if err := this.ParseForm(&form); err != nil {
this.Abort("401")
} else {
db := this.GetDB()
if !form.Validate() {
this.Data["form"] = form
var cats []*models.Category
db.QueryTable("category").All(&cats)
this.Data["Categories"] = cats
this.ConfigPage("article-editor.html")
for key, msg := range form.Errors {
fmt.Println(key, msg)
}
} else {
db.Insert(Art)
this.Data["Article"] = Art
this.ConfigPage("article.html")
}
}
}
Note: FormData is always accepted (even an empty form), form.Validate() is always returning 'true'... 0 errors on logs.
It's because your struct has a data type with map[string]interface{} which accepts any data type and converting it into a string try to be specific in data type
http://play.golang.org/p/xjs-jwMsr7
I have this function
func (e *MyError) Error() string {
return fmt.Sprintf("AT %v, %s", e.When, e.What)
}
But
as you see below, I never called it but how come it is called in the final output?
type MyError struct {
When time.Time
What string
}
func (e *MyError) Error() string {
return fmt.Sprintf("AT %v, %s", e.When, e.What)
}
func run() error {
return &MyError{
time.Now(), "it didn't work",
}
}
func main() {
if err := run(); err != nil {
fmt.Println(err)
}
}
fmt.Println and the other functions in pkg/fmt analyze the objects passed to it.
If it is an error, the function calls .Error() on the passed object and prints the string
returned by Error().
See the source for details. The code says:
switch v := p.field.(type) {
case error:
// ...
p.printField(v.Error(), verb, plus, false, depth)
return
// ...
}
The type of the passed object is checked in a type switch statement and in case of the object
implementing the error interface, v.Error() is used as value.