Using a switch to handle different types in an object map

Firstly apologies if my title is unclear or the wrong terminology is used - I can edit if anyone can suggest better :slight_smile:

I want to print on a web page the data for the userSessionID but the data is of different types. For example I tried to do a .(string) type assertion for Value in the Object Map but I got this error:

panic…interface conversion: interface {} is uint8, not *string

So I think it’s best to create a switch for Value, except I don’t know where to start, even from looking at the go docs.

type objectMapDefinition struct {
    	Value interface{}
    }

    const (
    	userSessionID = "User"
    )

    func RenderUserProfile(r http.ResponseWriter, session *sessions.Session) {
    	page := Model.Page{
    		TemplateFilename: []string{"UserProfile.template.html"},
    		ObjectMap:        objectMapDefinition{
    			Value: session.Values[userSessionID],
    		},
    	}
    }

Any help is much appreciated.

At which line does the panic occur?

From your code i don’t see where you have done a type assertion. Could you please include it. And like @christophberger has commented it would help if you provided us with the line raising the panic.

I have been able to reproduce @lennybeadle’s panic err.

https://play.golang.org/p/nO32HgYqKx

There are two ways you can do type assertions

  • When you are expecting any type use
    value.(type)
    and then use a switch on the types

  • When you are only interested in a particular type and you know the value will be of that type use
    value.(typeName) But this has one draw back if the value is of a different type then a panic will be raised

1 Like

Thanks for the answers, fortunately my error was fixed but not by me, but unfortunately the file has been overwritten so I have no way of showing other the solution but nevertheless the answers should be enough to provide others with a better idea.

Hello @lennybeadle

If you use Gorilla (http://www.gorillatoolkit.org/pkg/sessions), this is always []byte (or []uint8, are the same).

To convert it to string, try this :
string(session.Values[userSessionID][:])

I hope this will help you.
Cheer.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.