-1

I'm trying to make a Google Analytics Go library based off the auto generated package generated here

I have authenticated, got account summaries etc. so all is well until I try to construct a reporting request.

I am trying to init a struct ReportRequest that has the following:

type ReportRequest struct {

    DateRanges []*DateRange `json:"dateRanges,omitempty"`

    ...etc
}

How can I made a function that wraps this struct so I can pass in the values? Consulting the DateRange struct it seems simple enough, but I get messages about not passing in a slice pointer to DateRange which I can't figure out how to construct.

I have tried this:

func makeRequest(
    start, end string) *ga.GetReportsRequest {

    daterangep := &ga.DateRange{StartDate: start, EndDate: end}

    requests := ga.ReportRequest{}
    requests.DateRanges = daterangep

But get a compiler error:

cannot use daterangep (type *analyticsreporting.DateRange) as type []*analyticsreporting.DateRange in assignment

Is it possible to send in JSON? I see some MarshalJSON functions that I don't know if I can use,and the json declaration in the object but I'd prefer to be able to use Go objects.

Can anyone point to what I'm doing wrong?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
MarkeD
  • 2,500
  • 2
  • 21
  • 35
  • 1
    `&[]*analyticsreporting.DateRange{{StartDate: start, EndDate: end}}`. And replace `analyticsreporting` with `ga` if you renamed the import. – mkopriva Aug 04 '19 at 19:54
  • ... for more details see [link](https://golang.org/ref/spec#Composite_literals). – mkopriva Aug 04 '19 at 19:59
  • Thanks! It was `daterangep := []*ga.DateRange{{StartDate: start, EndDate: end}}` not including the `&` but compiler happy now - please do add ytour answer so I can accept it :) – MarkeD Aug 04 '19 at 20:06
  • Looks like my Q got voted down because this was VERY basic, apparently. – MarkeD Aug 05 '19 at 15:58

1 Answers1

1

To initialize a slice you can use a literal:

daterangep := []*ga.DateRange{{StartDate: start, EndDate: end}}

You can use make:

daterangep := make([]*ga.DateRange, 1)
daterangep[0] = &ga.DateRange{StartDate: start, EndDate: end}

Or you can declare it and then use append:

var daterangep []*ga.DateRange
daterangep = append(daterangep, &ga.DateRange{StartDate: start, EndDate: end})
mkopriva
  • 35,176
  • 4
  • 57
  • 71