-2

My question is somewhat related to this but rather than extending an existing type im trying to create my own. My goal is to have something like this, coming from java

JsonClient j = new JsonClient()
j.setUrl("x.com")
j.setMethod(GET)
j.setData("{crap: morecrap}")
String result = j.send

But in go the best i can do is

config := jsonclient.Config{}
config.Url = "http://foaas.com/version"
config.Data = []byte(`{datadatadata}`)
config.Method = "GET"

s, err := jsonclient.NewClient(&config)
checkErr(err)

response := jsonclient.Dial(s)

I do not wish to have a config object just to setup a jsonclient instance, since it only has meaning in the, dont hit me, jsonclient class so i should be able to do jsonclient.SetUrl and so on, seams more efficient and would help me understand a couple of key points im missing in go.

You can find the jsonclient here

Community
  • 1
  • 1
norwat
  • 218
  • 1
  • 11
  • 1
    Simply change the `NewClient` method to take the parameters directly instead of passing them via the object. Alternatively, make all the config members members of the client class. – Stephan Dollberg May 23 '15 at 14:38
  • How do i make all the config members members of the client class ? – norwat May 23 '15 at 15:42
  • 1
    Your question is unclear to me. Are you writing and wanting to change the API of `jsonclient` or is it a third party package you're using? If the later, you have no guarantee the config values themselves aren't need in `New` so you can't do much other just create the Config on the fly and don't store it; like so: https://play.golang.org/p/YJU7Peln3p – Dave C May 23 '15 at 16:40
  • This is a package i wrote, just for learning purposes. What i want, and i not sure if its possible in Go, is to create an instance of jsonclient, with all its structs and methods and get data based on the context of that package, being the context defined by me, the config part. Your example creates a copy of struct and only allows me to set and get properties, i wish to also run methods – norwat May 23 '15 at 18:17
  • Something like this https://play.golang.org/p/GOXA1ZXcIO but that works across packages – norwat May 23 '15 at 18:26
  • There is nothing in that playground program that won't work across packages. All the methods are exported, so could be called from other packages. – James Henstridge May 24 '15 at 04:17

1 Answers1

4

You can call methods on types from another package provided those methods are exported (that is, starting with a capital letter). So there is nothing stopping you from adding such methods to your type: you'd just need to name them e.g. SetUrl instead of setUrl.

James Henstridge
  • 42,244
  • 6
  • 132
  • 114
  • Heres a snippet of what i have now http://pastebin.com/hWAPVJr1 But on the main package i get `type jsonclient.Client has no field or method SetUrl)` i've tried setting the retrieval param as value and as pointer and got the same error – norwat May 23 '15 at 15:37