bytes.Reader, replacing underlying []byte array - pointers

I've been trying to find a nice way to hand off a Reader interface{} without recreating the methods associated with a io.Reader.
This is what I'm using:
type EZReader struct {
data *bytes.Reader
}
func (self *EZReader) Replace(input []byte) {
self.data = bytes.NewReader(input)
}
func (self *EZReader) Read(p []byte) (n int, err error) {
return self.data.Read(p)
}
It feels, not right, is there a better way to do this?
The idea is I can then hand off this io.Reader to a function and change out the underlying array as
I need it without having to reallocating the object that wants to use it, in this case the json decoder.

If you embed a field in a struct, all the methods of that field can be called on the struct, too. So if you write
type EZReader struct {
*bytes.Reader
}
you don't have to reimplement Read(). Such a field behaves as if it was named Reader. Notice that you can't avoid exposing the field this way.

Related

How can you bind a POST body to map?

I've been using Gin's ShouldBind() method to bind form data to a struct:
type UpdateUserInfoContext struct {
Country string `json:"country"`
EmailAddr string `json:"emailAddr"`
LoginID string `json:"loginID"`
UserName string `json:"username"`
}
func (h *handler) updateUserInfo(ctx *gin.Context) {
var json UpdateUserInfoContext
if err := ctx.ShouldBind(&json); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
h.service.UpdateUserPassword(json)
ctx.JSON(http.StatusOK, "success")
}
But now I need to build a large, dynamic UPDATE SQL based on what is and isn't present in the body of a POST request. Since ShouldBind() binds to a struct I can't iterate over the values in the body without using reflection. I figured an easier way would be to see if there's a method to bind the requests to a map instead of a struct. There is the context method PostFormMap(key string), however as far as I can tell from the example given here (https://github.com/gin-gonic/gin#another-example-query--post-form), this method requires the values correspond to to the argument key in the request body. Does anyone have any experience doing this? Thank you!
package main
import (
"fmt"
"encoding/json"
)
func main() {
strbody:=[]byte("{\"mic\":\"check\"}")
mapbody:=make(map[string]string)
json.Unmarshal(strbody,&mapbody)
fmt.Println(fmt.Sprint("Is this thing on? ", mapbody["mic"]))
}
//returns Is this thing on? check
https://play.golang.org/p/ydLuLsY8qla

Setting a value via an interface in go

In the following example, I'd like to call the setvalue() of the b object via an interface procedure.
I'd like to use an interface because I need to insert different kinds of objects in a list, possibly very big, each obeying a common interface.
However the compiler complains with the following error :
./tests.go:27:6: cannot use newbox(3) (type box) as type container in assignment:
box does not implement container (setValue method has pointer receiver)
Probably I have to define the interface differently, but how?
I know I could transform the setvalue procedure in a function, returning the updated box, but since the object can be very large, and he procedure will be called several times, i'd like to pass the object via a pointer.
Really isn't there a way to define an interface method that receive the calling structure via a pointer?
package main
import "fmt"
type container interface {
setValue (val int)
}
//--------------------------------------
// box is a kind of container
type box struct {
value int
}
func newbox (x int) box {
return box {x}
}
func (cnt *box) setValue(val int) {
(*cnt).value = val
}
// -----------------------------------------------
func main() {
var b container = newbox(3) // HERE IS THE ERROR
fmt.Printf("%v\n",b)
b.setValue(5)
fmt.Printf("%v\n",b)
}

Go reflect with gorm library

I am using gorm package (https://github.com/jinzhu/gorm) as my database library in golang. I have many classes (database tables) like "Hotel" or "Package". Duplicating code is not good programming practice. As a silly example - lets assume I want to get first object from each table. I can write this method (GetFirstHotel, GetFirstPackage...) for each object. But better way would be to have just a single method GetFirstItem, where I would use first param to create object with same class as parameter, then pass it to gorm, which will fill it with data from database, then return it as interface{}. I tried to use reflect for that, but failed, because I probably don't understand it much.
Maybe I just didn't discover some function in gorm library, or I can't use reflect package properly. How should I implement GetFirstItem function. Is it possible to have this implemented, or should I rather repeat my code?
package main
import (
"github.com/jinzhu/gorm"
)
var db gorm.DB
type Hotel struct {
ID int64
Name string
Lat float64
Lon float64
}
type Package struct {
ID int64
Name string
Text string
}
func GetFirstHotel() (hotel Hotel) {
db.First(&hotel)
}
func GetFirstPackage() (pack Package) {
db.First(&pack)
}
func main() {
var firstHotel, firstPackage interface{}
//first method
firstHotel = GetFirstHotel()
firstPackage = GetFirstPackage()
//method i want to use
firstHotel = GetFirstItem(Hotel{})
firstPackage = GetFirstItem(Package{})
}
func GetFirstItem(item interface{}) interface{} {
//how to implement this?
//probably with some use of reflect package
}
The db.First method returns db reference and hydrates the row into the passed structure.
The closest to your desired method is
func GetFirstItem(item interface{}) error {
return db.First(item).Error
}
This simply requires you keep a reference to the parameter
var firstHotel &Hotel{}
err := GetFirstItem(firstHotel)
Returning the hydrated object for all types would required type parameters (generics). I think you'll find the current situation is workable within limits.
see also: Why no generics in Go?

How I can write a single function to work with different types

Given the following example, is it anyhow possible to create a function that can literally reproduce (not only get the reflect.Type) the actual type for further manipulation? I know go is statically typed and although it's very cool that I can pass any struct to a function that defines an interface parameter, is there any chance I can do more the other way around?
I already looked into the reflect package but only found stuff that returned a reflect.Type or reflect.Value. I used the New() method which returned a new reflect.Value - and there I couldn't set any fields. Maybe someone experienced with the reflect package can tell me if this is definitely possible or not - or if there's another way to do it.
package main
import "fmt"
type User struct {
Name string
}
func main() {
user := User{Name:"FooBar"}
DoSomethingGenericWithStruct(user)
}
func DoSomethingGenericWithStruct(i interface{}) {
// access fields of i ...
// or create slice of type of i ([]User) ...
// or instantiate new object of type of i (new User) ...
// ...
}
You would have to pass a pointer to your struct to be able to modify it.
Also keep in mind that using reflection has a high runtime performance cost.
func DoSomethingGenericWithStruct(i interface{}) {
val := reflect.ValueOf(i)
if val.Kind() != reflect.Ptr {
panic("need a pointer")
}
val = val.Elem() // now you can modify it
// add error checking and such, this will panic if it's not a struct or there's no "Name" field
val.FieldByName("Name").SetString("stuff")
}
playground
To create a new element and assign it:
val = val.Elem()
nval := reflect.New(val.Type()).Elem() // create a new struct of the same type
nval.FieldByName("Name").SetString("stuff")
val.Set(nval)
to modify the actual struct, not reflect.Value, you will have to get the interface{} to it then assert it to your type, for example:
nval := reflect.New(val.Type()).Elem() // create a new struct of the same type
user := nval.Interface().(User)
user.Name = "Stuff"
val.Set(reflect.ValueOf(user))

extending structs with (relatively) unknown/arbitrary methods, go reflection(or avoiding reflection)

The below does not work obviously:
Arbitrary := struct {
field1 string
field2 string
}{"a", "b"}
fmap := make(map[string]func(string) string)
fmap["fone"] = func(s string) string { fmt.Printf("function fone: %s", s) }
fmap["ftwo"] = func(s string) string { fmt.Printf("function ftwo: %s", s) }
// probably ok, as simple examples go, to this point where reflection needs to be used
// the below does not work
Arbitrary.fone = fmap["fone"]
Arbitrary.fone("hello")
The above is the core of what I'm trying to do: create a struct with values, and then create methods on the struct from a map of functions, or functions passed in. Basically I have a structure with data & ambiguous behavior that needs to be extended with methods unknown until creating the type.
I'm looking for the obvious & inevitable:
How to do this in Go
Why this shouldn't be done, or can't be done in Go (its possible with the reflect package, I just haven't found examples or reasoned thorough it yet)
How this should be done in Go (some sort of interface construct I've not figured out wholly. I've tried an interface which can handle the behavior; but it doesn't account for other behaviors that might be added, at the least I haven't figured out interface usage fully yet which is part of the issue)
If you're a person needing complexity here is the start of the actual task I'm trying to accomplish, making that structs behavior extendable.
I completely misunderstood the question.
NO, you can't create a new struct out of thin air and assign fields to it, also even if you could, for the love of everything that's holy, don't do that.
You can use multiple interfaces for example:
type Base interface {
Id() int //all structs must implement this
}
type Foo interface {
Base
Foo()
}
type Bar interface {
Base
Bar()
}
then make a map[string]Base, and you can assert the value later.
//leaving the original answer as a different approach to the problem.
While usually that kind of stuff is done using reflection, if you have a limited number of accepted "callbacks" you can use type assertion and an interface{} map, dropping the need for reflection.
var ctx = &Ctx{"Hello"}
var funcs = map[string]interface{}{
"m3": ctx.Do,
"m4": func(c *Ctx) { fmt.Println("ctx:", c) },
}
type Ctx struct {
Name string
}
func (c *Ctx) Do() {
fmt.Printf("Do: %+v\n", c)
}
func call(m string) {
if f, ok := funcs[m]; ok {
switch fn := f.(type) {
case func():
fn()
case func(*Ctx):
fn(&Ctx{"Hello world"})
default:
panic(fn)
}
}
}
playground

Resources