can we pass extra parameter to a beego router - sql

type MainController struct {
beego.Controller
}
func (this *MainController) Post() {
var datapoint User
req := this.Ctx.Input.RequestBody
json.Unmarshal([]byte(req), &datapoint)
this.Ctx.WriteString("hello world")
// result := this.Input()
fmt.Println("input value is", datapoint.UserId)
}
this is normal beego router which executes on url occurrence. I want something like
type MainController struct {
beego.Controller
}
func (this *MainController,db *sql.DB) Post() {
fmt.Println("input value is", datapoint.UserId)
}
in order to use database connection pointer. is this possible to achieve this using go...if not please suggest

You can't do this in golang
type MainController struct {
beego.Controller }
func (this *MainController,db *sql.DB) Post() {
fmt.Println("input value is", datapoint.UserId)
}
the declaration in the form
function (c *MainController)Post()
means that Post is a method for the MainController struct you can pass variable into it.
My suggestion is you declare the db pointer as a global variable in your package like below then you will be able to use it inside the Post function
type MainController struct {
beego.Controller
}
var db *sql.DB
func (this *MainController) Post() {
//you can now use the variable db inside here
fmt.Println("input value is", datapoint.UserId)
}
but considering this is Beego which uses the MVC pattern you can do all this from within the model. I suggest you take a look at their awesome documentation here

Related

Actual type lost on call

Another question on polymorphism in Go, references: Embedding instead of inheritance in Go, https://medium.com/#adrianwit/abstract-class-reinvented-with-go-4a7326525034
Motivation: there is an interface (with some methods for dealing with "the outside world") and a bunch of implementation structs of that interface.
There is a "standard" implementation of some of these methods, where common logic should be put in one place with delegation to (new) methods in the structs-implementing-the-interface ("subclasses" is not a word).
I've read the medium link above and wrote some test code. Alas, it does not work the way I expect, the actual type of a struct is lost when the call on the interface is indirect.
In C++ this is called "based class slicing" and happens when passing a polymorphic class by value. In my Go test code I'm careful to pass by reference, and then Go is not C++ (or Java).
Code: https://play.golang.org/p/lxAmw8v_kiW
Inline:
package main
import (
"log"
"reflect"
"strings"
)
// Command - interface
type Command interface {
Execute()
getCommandString() string
onData(data string)
}
// Command - implementation
type Command_Impl struct {
commandString string
conn Connection
}
func newCommand_Impl(conn Connection, data string, args ...string) Command_Impl {
var buf strings.Builder
buf.WriteString(data)
for _, key := range args {
buf.WriteString(" ")
buf.WriteString(key)
}
return Command_Impl {
conn: conn,
commandString: buf.String(),
}
}
func (self *Command_Impl) Execute() {
log.Printf("Command Impl Execute: %s", reflect.TypeOf(self))
self.conn.execute(self)
}
func (self *Command_Impl) getCommandString() string {
return self.commandString
}
func (self *Command_Impl) onData(data string) {
log.Printf("Command Impl onData: %s", data)
}
// Command - subclass
type Command_Login struct {
Command_Impl
onDataCalled bool
}
func newCommand_Login(conn Connection) *Command_Login {
return &Command_Login{
Command_Impl: newCommand_Impl(conn, "LOGIN", "user#foo.com", "pa$$w0rd"),
}
}
func (self *Command_Login) onData(data string) {
log.Printf("Command Login onData: %s", data)
self.onDataCalled = true
}
// Connection - interface
type Connection interface {
execute(command Command)
}
// Connection - impelementation
type Connection_Impl struct {
}
func newConnection_Impl() *Connection_Impl {
return &Connection_Impl{}
}
func (self *Connection_Impl) execute(command Command) {
log.Printf("Connection execute: %s, %s", command.getCommandString(), reflect.TypeOf(command))
command.onData("some data")
}
func main() {
conn := newConnection_Impl()
command := newCommand_Login(conn)
// I expect command.Execute to preserve actual type of command all the way through
// command.conn.execute(self) and then the callback onData from connection to command
// to use the onData in Command_Login
//
// This does not happen however, the test fails
command.Execute()
// This does preserve actual type of command, but isn't how I'd like to connect
// commands and connections...
//
//conn.execute(command)
if command.onDataCalled {
log.Printf("*** GOOD: Command_Login onData ***was*** called")
} else {
log.Printf("*** ERROR: Command_Login onData ***not*** called")
}
}
There is a Command interface which defines some methods.
There is a Command_Impl struct where I'd like to implement some common code that would further delegate to finer-grained methods in more structs that implement the same interface ("subclass is not a word"), similar to:
https://stackoverflow.com/a/1727737/2342806
The question:
Calling command.Execute() which in turn calls conn.execute(self) ends up "slicing" the Command_Login object and inside Connection.execute it's turned into Command_Impl. As a result, onData interface method defined for Command_Login do not get called.
If I call conn.execute(command) then the right onData does get called, but this is not how I'd like to connect my objects (e.g. Command already has a Connection, but basically what I wrote above about reusing implementation).
In Go terms, I'm trying to come up with a way to delegate implementation by embedding, and have a way to for the delegate to call back into the enclosing type (which fine-tunes the delegate's logic).
Alas, it seems to not be supported by Go (at least I can't find a way) - once you delegate to an embedded struct, your calls stay entirely there in the embedded struct, it "does not know" that it's part of a larger object which may be wanting to override some of the embedded struct's methods.
What about delegating implementation by implementing the Execute interface at the shallowest depth you need?
func (self *Command_Login) Execute() {
self.Command_Impl.Execute()
log.Printf("Command Login Execute: %s", reflect.TypeOf(self))
self.onDataCalled = true
}
https://play.golang.org/p/HvaKHZWIO5W

how to deal with embedded interfaces and share data between them

I would like to better understand how to use interfaces, mainly to split code in reusable components and at the same time make it more easy for testing, currently my main question is how to share/get data between the interfaces that belong to a main interface, for example:
https://play.golang.org/p/67CQor1_pY
package main
import (
"fmt"
)
type MainInterface interface {
SubInterfaceA
SubInterfaceB
}
type SubInterfaceA interface {
MethodA()
GetterA(s implementMain)
}
type SubInterfaceB interface {
MethodB()
GetterB(s implementMain)
}
type implementA struct{}
func (ia *implementA) MethodA() { fmt.Println("I am method A") }
func (ia *implementA) GetterA(s implementMain) {
fmt.Println(s.Data)
}
type implementB struct{}
func (ib *implementB) MethodB() { fmt.Println("I am method B") }
func (ib *implementB) GetterB(s implementMain) {
fmt.Println(s.Data)
}
type implementMain struct {
Data string
SubInterfaceA
SubInterfaceB
}
func New(d string) implementMain {
return implementMain{
Data: d,
SubInterfaceA: &implementA{},
SubInterfaceB: &implementB{},
}
}
func main() {
var m MainInterface
m = New("something")
fmt.Println(m.(implementMain).Data)
m.MethodA() // prints I am method A
m.MethodB() // prints I am method B
m.GetterA(m.(implementMain)) // prints "something"
m.GetterB(m.(implementMain)) // prints "something"
}
In the above code, within the methods of struct implementA or implementB how to access the struct elements of the parent holder implementMain that implements MainInterface without passing it as an argument?
with holder struct I mean:
type implementMain struct {
Data string
SubInterfaceA
SubInterfaceB
}
If I am right SubInterfaceA and SubInterfaceB are embedded and help to make the struct implementMain satisfy the MainInterface:
type MainInterface interface {
SubInterfaceA
SubInterfaceB
}
But within the embedded methods of the SubInterfaceA or subInterfaceB what is the best practice to use in order to be available to get the data string?
I created Getter(s implementMain) method and passed the holder struct, but had to cast type:
m.GetterA(m.(implementMain))
I don't know if by satisfying a interface, all the involved interfaces can become part of the same structure scope and if they do, how to get/share data between them or either between its components?, for example besides been available to reach data string how from SubInterfaceA get/access SubInterfaceB

Call generic function from non-generic function in Swift

MMCondition is a protocol defined in Swift, but interoperates with Objective-C (annotated with #objc).
#objc public protocol MMCondition {
static var name: String { get }
static var isMutuallyExclusive: Bool { get }
}
I have the following code:
// addCondition cannot be generic as I want it to be accessible from Objective-C as well.
public func addCondition(condition: MMCondition) {
// How do I initialize OperationConditionImplementer here?
let operationCondition = OperationConditionImplementer(condition: condition) // doesn't compile
// Error: Cannot invoke initializer for type 'OperationConditionImplementer<T>' with an argument list of type '(condition: MMCondition)'
// Can I use condition.dynamicType to init OperationConditionImplementer somehow?
}
struct OperationConditionImplementer<T: MMCondition> {
let condition: T
static var name: String {
return "Silent<\(T.name)>"
}
static var isMutuallyExclusive: Bool {
return T.isMutuallyExclusive
}
init(condition: T) {
self.condition = condition
}
}
From Objective-C, you can't use generics as stated in the documentation.
You’ll have access to anything within a class or protocol that’s
marked with the #objc attribute as long as it’s compatible with
Objective-C. This excludes Swift-only features such as those listed
here:
Generics
...
So you need to remove completely the generics code. One possible solution might be:
#objc protocol MMCondition {
static var name: String { get }
static var isMutuallyExclusive: Bool { get }
}
struct OperationConditionImplementer {
let condition: MMCondition
var name: String {
return "Silent<\(condition.dynamicType.name)>"
}
var isMutuallyExclusive: Bool {
return condition.dynamicType.isMutuallyExclusive
}
init(condition: MMCondition) {
self.condition = condition
// Here decide comparing types
if condition.dynamicType === ExampleCondition.self {
print(condition.dynamicType.name)
}
}
}
So for instance, if you try it out in a playground:
class ExampleCondition: NSObject, MMCondition {
static var name: String = "ExampleCondition"
static var isMutuallyExclusive: Bool = false
}
let example = OperationConditionImplementer(condition: ExampleCondition())
You'll see "ExampleCondition" printed.
If you eventually switch to pure Swift, you need to specify T when initializing a OperationConditionImplementer.
You can achieve that defining the addCondition method as:
func addCondition<T: MMCondition>(condition: T) {
let a = OperationConditionImplementer<T>(condition: condition)
}
Since Swift 2.0 instances of generic classes can implement Objective-C protocols. What won't be possible I believe is having a struct implement the protocol. In fact I expect that your protocol may need to inherit from NSObjectProtocol to be usable in Objective-C which would then prevent you from implementing the protocol with structs or enums.
You also rightly mention that you can't access generic functions from Objective-C.
For a concrete example of using a generic to fulfil an Objective-C protocol have a look at this blog post.

How to separate models from controllers in testing?

So I wanted to isolate controllers from models in testing so that I could easily figure out stuff if troubles arise. Before, I just hit the endpoints with mock data but it was difficult to troubleshoot because the test runs from the router all the way to the datastore. So I'm thinking maybe I'll just create two versions(MockController vs Controller) for each controller(and model) and use one depending on the value of the mode variable. In a nutshell, this is how I plan to implement it.
const mode string = "test"
// UserModelInterface is the Interface for UserModel
type UserModelInterface interface {
Get()
}
// UserControllerInterface is the Interface for UserController
type UserControllerInterface interface {
Login()
}
// NewUserModel returns a new instance of user model
func NewUserModel() UserModelInterface {
if mode == "test" {
return &MockUserModel{}
} else {
return &UserModel{}
}
}
// NewUserController returns a new instance of user controller
func NewUserController(um UserModelInterface) UserControllerInterface {
if mode == "test" {
return &MockUserController{}
} else {
return &UserController{}
}
}
type (
UserController struct {um UserModelInterface}
UserModel struct {}
// Mocks
MockUserController struct {um UserModelInterface}
MockUserModel struct {}
)
func (uc *UserController) Login() {}
func (um *UserModel) Get() {}
func (uc *MockUserController) Login() {}
func (um *MockUserModel) Get() {}
func main() {
um := NewUserModel()
uc := NewUserController(um)
}
This way I could just skip sql query in the MockUserController.Login() and only validate the payload and return a valid response.
What do you think of this design? Do you have a better implementation in mind?
I would let the code that calls NewUserController() and NewUserModel() decide whether to create a mock or real implementation. If you use that pattern of dependency injection all the way up to the top your code will become clearer and less tightly coupled. E.g. if the user controller is used by a server, it would look something like along the lines of:
Real:
u := NewUserController()
s := NewServer(u)
In tests:
u := NewMockUserController()
s := NewServer(u)
I would try a more slim variant spread over a models and a controllers package, like this:
// inside package controllers
type UserModel interface {
Get() // the methods you need from the user model
}
type User struct {
UserModel
}
// inside package models
type User struct {
// here the User Model
}
// inside package main
import ".....controllers"
import ".....models"
func main() {
c := &controllers.User{&models.User{}}
}
// inside main_test.go
import ".....controllers"
type MockUser struct {
}
func TestX(t *testing.T) {
c := &controllers.User{&MockUser{}}
}
For controller testing consider the ResponseRecorder of httptest package

Swift : Parse subclass dynamic var dont get included when retrieving object

I can´t get the object properties when retrieving an object from Parse Data Browser. This happened after I changed from "#NSManaged var friends" to "dynamic var friends". Even "name" show nil in User.logInWithUsernameInBackground block which is crazy because the login succeeds. The ACL for User is set to "public read".
User object:
class User : PFUser, PFSubclassing {
dynamic var friends:[User]!
dynamic var name:String!
override class func load() {
self.registerSubclass()
}
}
Retrieving the User along with the friends. println showing nil
var query = User.query()
query.includeKey("friends")
query.getObjectInBackgroundWithId(currentUser.objectId) {
(pfObject: PFObject!, error: NSError!) -> Void in
if pfObject != nil {
var user = pfObject as User
var friends = user.friends as [User]
println("friends: \(friends)") //nil
} else {
println(error)
}
}
Login. println showing nil
User.logInWithUsernameInBackground(USERNAME, password:PASSWORD) {
(user: PFUser!, error: NSError!) -> Void in
if user != nil {
println("Logged in with user: \(user.name)") //nil
} else {
println(error)
}
}
Looking a little deeper for you, it seems the hurdle is a misunderstanding of what the dynamic modifier in Swift does. Apparently, dynamic in Swift is used for Key-Value observing, not declaring a variable's accessors to be defined at runtime (what #dynamic does in Objective-C)
See this for a description of dynamic in Swift https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/AdoptingCocoaDesignPatterns.html#//apple_ref/doc/uid/TP40014216-CH7-XID_8
and this for the description of why #NSManaged works the way #dynamic does in Objective-C
https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/BuildingCocoaApps/WritingSwiftClassesWithObjective-CBehavior.html#//apple_ref/doc/uid/TP40014216-CH5-XID_66
With xCode 6.1.1 I was able to get this working without the bridging header but I did need to use #NSManaged. Here's how... Just:
import Parse
at the top of the calling module. For the class declaration .swift file dynamic didn't work so I needed to use #NSManaged for the variable types to get them to link to the Parse class variables successfully. Like this:
class PSCategory : PFObject, PFSubclassing {
override class func load() {
self.registerSubclass()
}
class func parseClassName() -> String! {
return "Category"
}
#NSManaged var Name: String
}
Then in my query all the names are dynamically linked:
var query = PSCategory.query() // PFQuery(className: "Category")
query.cachePolicy = kPFCachePolicyCacheElseNetwork // kPFCachePolicyNetworkElseCache
query.maxCacheAge = 60 * 60 * 24 // One day, in seconds.
query.findObjectsInBackgroundWithBlock {
(categories: [AnyObject]!, error: NSError!) -> Void in
if error == nil {
for abstractCategory in categories {
let category = abstractCategory as PSCategory
NSLog("Category Name: %#", category.Name)
}
} else {
NSLog("Unable to retrieve categories from local cache or network")
}
}