Golang: create a slice of strutcs - list

I want to create a list of structs that can be returned by a function in a manner as it is in the go-github package.
But what is the correct way to create and populate such a list?
I found two ways, e.g., using the append():
...
allowedRepos := strings.Fields("repo1, repo2")
actualRepos := []Repos{}
actualRepos = append(actualRepos, Repos{Name: "repo1", URL: "gth.com/repo1"})
actualRepos = append(actualRepos, Repos{Name: "repo2", URL: "gth.com/repo2"})
...
And by a "direct initialization:
...
actualRepos := []Repos{
Repos{Name: "repo1", URL: "gth.com/repo1"},
Repos{Name: "repo2", URL: "gth.com/repo2"},
}
They works but both look bit awkward and wrong.
So - what is the best way to do it?
It looks like need to create it using pointer but can't make it work.

but both look bit awkward and wrong
Actually there is nothing wrong, both approaches are correct and valid.
The only difference - is slice population time.
In 2nd approach you're populating slice during development time, it means this code:
actualRepos := []Repos{
Repos{Name: "repo1", URL: "gth.com/repo1"},
Repos{Name: "repo2", URL: "gth.com/repo2"},
}
always will create slice with 2 elements in it.
But wit 1st approach you can populate slice in runtime using append(), like:
actualRepos := []Repos{}
for _, repo := range allRepos {
actualRepos = append(actualRepos, repo)
}
so now all depends on allRepos and now this code have dynamic behaviour which is determined in runtime.
It looks like need to create it using pointer
Please pay attention that slice itself passes by reference, for example:
s := [...]string{"r", "o", "a", "d"}
s2 := s[:]
s[3] = "x"
Result will be:
// s = [r o a x], s2 = [r o a x]

Related

remove "?show=false" using regex [duplicate]

I looking for regular expression to use in my javascript code, which give me last part of url without parameters if they exists - here is example - with and without parameters:
https://scontent-fra3-1.xx.fbcdn.net/v/t1.0-9/14238253_132683573850463_7287992614234853254_n.jpg?oh=fdbf6800f33876a86ed17835cfce8e3b&oe=599548AC
https://scontent-fra3-1.xx.fbcdn.net/v/t1.0-9/14238253_132683573850463_7287992614234853254_n.jpg
In both cases as result I want to get:
14238253_132683573850463_7287992614234853254_n.jpg
Here is this regexp
.*\/([^?]+)
and JS code:
let lastUrlPart = /.*\/([^?]+)/.exec(url)[1];
let lastUrlPart = url => /.*\/([^?]+)/.exec(url)[1];
// TEST
let t1 = "https://scontent-fra3-1.xx.fbcdn.net/v/t1.0-9/14238253_132683573850463_7287992614234853254_n.jpg?oh=fdbf6800f33876a86ed17835cfce8e3b&oe=599548AC"
let t2 = "https://scontent-fra3-1.xx.fbcdn.net/v/t1.0-9/14238253_132683573850463_7287992614234853254_n.jpg"
console.log(lastUrlPart(t1));
console.log(lastUrlPart(t2));
May be there are better alternatives?
You could always try doing it without regex. Split the URL by "/" and then parse out the last part of the URL.
var urlPart = url.split("/");
var img = urlPart[urlPart.length-1].split("?")[0];
That should get everything after the last "/" and before the first "?".

Migration to Swift 3

I have a variable called service, like so:
var service: AnyObject = [] //Swift 2.3
My question is how to migrate this to Swift 3. I'm a noob in iOS, I've looked in Internet but could't get it.
PS. I get an error "Contextual type 'AnyObject' cannot be used with array literal"
Thanks in advance!
What you were doing was always wrong. If you have no value to supply at initialization time, use an Optional. Ideally you should declare this as the actual type of value that it will be when gets a value (rather than a catch-all type such as AnyObject). But if you can't do that, then just use Any?:
var service : Any?
Or, if this thing's type is known — for example, if you know it's going to be a Dictionary — then declare it as a Dictionary, possibly by supplying an empty Dictionary, like this:
var service = [AnyHashable:Any]()
var service = [AnyObject]() will work.
Here is an example of using it in Swift -3
var service = [AnyObject]() //Swift 3
service = ["a" as AnyObject,"b" as AnyObject]
print(service)
Output:
a,b

Get an automatic list of ExpressJS params

I am trying to get a list of all of the parameters in a path from a get request.
app.get('/*',function(req, res) {
console.log(req.params[0]);
res.send('testing');
});
However, when I go to the url localhost/test/test1, the params[0] object is 'test/test1'.
Is there any way to make it split the url in to params without doing '/*/*'. I want to be able to put in as many values as I need without worrying about naming or counting them.
The ideal input/output would be:
URL: localhost/arg1/arg2/arg3
params[0] = 'arg1'
params[1] = 'arg2'
params[2] = 'arg3'
Thanks.
A simple split will work:
var splitParams = params[0].split('/');

Query parameters for GET requests using Akka HTTP (formally known as Spray)

One of the features of Akka HTTP (formally known as Spray) is its ability to automagically marshal and unmarshal data back and forth from json into case classes, etc. I've had success at getting this to work well.
At the moment, I am trying to make an HTTP client that performs a GET request with query parameters. The code currently looks like this:
val httpResponse: Future[HttpResponse] =
Http().singleRequest(HttpRequest(
uri = s"""http://${config.getString("http.serverHost")}:${config.getInt("http.port")}/""" +
s"query?seq=${seq}" +
s"&max-mismatches=${maxMismatches}" +
s"&pam-policy=${pamPolicy}"))
Well, that's not so pretty. It would be nice if I could just pass in a case class containing the query parameters, and have Akka HTTP automagically generate the query parameters, kind of like it does for json. (Also, the server side of Akka HTTP has a somewhat elegant way of parsing GET query parameters, so one would think that it would also have a somewhat elegant way to generate them.)
I'd like to do something like the following:
val httpResponse: Future[HttpResponse] =
Http().singleRequest(HttpRequest(
uri = s"""http://${config.getString("http.serverHost")}:${config.getInt("http.port")}/query""",
entity = QueryParams(seq = seq, maxMismatches = maxMismatches, pamPolicy = pamPolicy)))
Only, the above doesn't actually work.
Is what I want doable somehow with Akka HTTP? Or do I just need to do things the old-fashioned way? I.e, generate the query parameters explicitly, as I do in the first code block above.
(I know that if I were to change this from a GET to a POST, I could probably to get it to work more like I would like it to work, since then I could get the contents of the POST request automagically converted from a case class to json, but I don't really wish to do that here.)
You can leverage the Uri class to do what you want. It offers multiple ways to get a set of params into the query string using the withQuery method. For example, you could do something like this:
val params = Map("foo" -> "bar", "hello" -> "world")
HttpRequest(Uri(hostAndPath).withQuery(params))
Or
HttpRequest(Uri(hostAndPath).withQuery(("foo" -> "bar"), ("hello" -> "world")))
Obviously this could be done by altering the extending the capability of Akka HTTP, but for what you need (just a tidier way to build the query string), you could do it with some scala fun:
type QueryParams = Map[String, String]
object QueryParams {
def apply(tuples: (String, String)*): QueryParams = Map(tuples:_*)
}
implicit class QueryParamExtensions(q: QueryParams) {
def toQueryString = "?"+q.map{
case (key,value) => s"$key=$value" //Need to do URL escaping here?
}.mkString("&")
}
implicit class StringQueryExtensions(url: String) {
def withParams(q: QueryParams) =
url + q.toQueryString
}
val params = QueryParams(
"abc" -> "def",
"xyz" -> "qrs"
)
params.toQueryString // gives ?abc=def&xyz=qrs
"http://www.google.com".withParams(params) // gives http://www.google.com?abc=def&xyz=qrs

Golang can't ExecuteTemplate

I need to ExecuteTemplate (text and html). I have next snippet:
import ("text/template")
...
test_path := "/cnaize/home/test.txt"
testTmpl := template.New(test_path)
var test bytes.Buffer
if err := testTmpl.ExecuteTemplate(&test, test_path, mm.Args); err != nil {
return err
}
but I have error invalid memory address or nil pointer dereference in ExecuteTemplate. When I change first line to import ("html/template"), I have "/cnaize/home/test.txt" is an incomplete template error.
My test.txt:
Test
Where may be a problem?
EDITED:
I know about documentation, but I found this solution in https://github.com/arkxu/gomail/blob/master/message.go and it's exactly what I need, because I don't know how to set args in template.ParseFiles(). template.New() with folder name is ok. And my mm.Args is map[message:Hello there!], I've checked it.
There are two things wrong here:
template.New() initializes an empty template with the given name, you are giving a path, which is ok, but it probably is not what you want. Please read the documentation before using libraries naively.
You are probably looking for: template.ParseFiles()
what is mm.Args? From that snippet alone and the error I would guess mm is nil.