0

I have a couple of structures, like:

type SomeObject struct {
   sample int
}

I want to fill the sample variable based on what I get in the request body. To do this, I want to create a function, pass request body as a string to it, create an empty structure inside, fill the structure with data, return it, and replace chosen structure with this.

How do I do this? What do I return from the function? Is there a way to do this?

2 Answers 2

1

If you're dealing with multiple types then you should make your method return an interface{}. For all of the applicable types, create a convenience method like;

func NewSomeObject(reqBody string) *SomeObject {
     return &SomeObject{sample:reqBody}
}

Which takes a string and returns a new instance of the type with that field set to whatever was passed in. Your question is missing information about how you determine which type should be instantiated but assuming you have a few, you'll likely need an if/else or a switch in the method which receives the request body so to give a very vague example it would be something like;

func ProcessRequest(reqBody string) interface{} {
      if someCondition {
           return NewSomeObject(reqBody)
      } else if otherCondition {
           return NewSomeOtherObject(reqBody)
      } // potentially several other statements like this
      return nil // catch all, if no conditions match
}
Sign up to request clarification or add additional context in comments.

Comments

1

How about

func foo (s *SomeObject) {
    s.sample = 123
}

or

func (s *SomeObject) foo() {
    s.sample = 123
}

1 Comment

Yes and for get request body, pass in parameters a string for request FormValue or a pointer on request

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.