Declared but not used - go

I am new to Golang. I am confused why I got the error that partial is not used in the code below?
// Using var keyword
var partial string
for i, request := range requestVec {
if i == (len(requestVec)-1) && !strings.Contains(request, "\r\n\r\n") {
partial = request
break
}
}
I assign request to partial in the if statement.

It is a compiler error in Go to declare a variable without using it.
In the code in you're example the variable partial is never used, only assigned, so is seen as unused. If you added additional code that read the variable then the error would be resolved. For example
var partial string
for i, request := range requestVec {
if i == (len(requestVec)-1) && !strings.Contains(request, "\r\n\r\n") {
partial = request
break
}
}
fmt.Println(partial) // We are now using `partial`

Related

How do I append to all string values inside a struct?

I have a struct defined in fruits.go
package domain
type AppleImages struct {
Front string `json:"frontImage"`
Back string `json:"backImage"`
Top string `json:"topImage"`
}
And I defined the same in process.go (which returns this data to the handler). This definition is only for demonstration purposes since I'm getting values from the database using gorm so we cannot append the required URL here.
package process
func getApple() (apple domain.Apple){
apple = domain.Apple{
Front: "front-image.png"
Back: "back-image.png"
Top: "top-image.png"
}
return
}
For my output is want to return
{
frontImage: "https://www.example.com/front-image.png",
backImage: "https://www.example.com/back-image.png",
topImage: "https://www.example.com/top-image.png",
}
I don't want to manually add https://www.example.com/ to each of the images in the struct.
Is there a way of parsing through the struct and automatically appending this string to all existing values?
Use gorm AfterFind hook. Every time after load data from database gorm call AfterFind and your data will be updated for Apple model. Then you don't need to manually do it after every time fetching from the database.
func (u *Apple) AfterFind() (err error) {
u.Front= "https://www.example.com/"+ u.Front
u.Back= "https://www.example.com/"+ u.Back
u.Top= "https://www.example.com/"+ u.Top
return
}
See details here
Is there a way of parsing through the struct and automatically appending this string to all existing values?
No.
I don't want to manually add https://www.example.com/ to each of the images in the struct.
Go provides no magic for thing to happen without you programming it. You must do this "manually".
You could use reflect to add a prefix for each filed in the struct.
See details here.
func getApple() (apple domain.Apple) {
apple = domain.Apple{
Front: "front-image.png",
Back: "back-image.png",
Top: "top-image.png",
}
addURL(&apple, "https://www.example.com/")
//fmt.Println(apple)
return
}
func addURL(apple *domain.Apple, url string) {
structValue := reflect.ValueOf(apple).Elem()
for i := 0; i < structValue.NumField(); i++ {
fieldValue := structValue.Field(i)
// skip non-string field
if fieldValue.Type().Kind() != reflect.String {
continue
}
structValue.Field(i).SetString(url + fieldValue.String())
}
}

How to parse array inside form post

I currently have a form post that is coming in like
{
"stuff":"cool text",
"otherthing":"neat thing",
"captions":[
{"first":"the list",
"second":"how are you"},
{"first":"wow",
etc....
]
}
Now I don't know how many captions there will be. It might be one in the array, it might be twenty.
I have set up two structures as well
type ThingContext struct {
Stuff string `json:"stuff"`
OtherThing string `json:"otherthing"`
Captions []ArrayText `json:"captions"`
}
type ArrayText struct {
First string `json:"first"`
Second string `json:"second"`
}
And in my golang function I have something like this
func (c *ThingContext) SetThingContext(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) {
if err := req.ParseForm(); err != nil {
}
c.Stuff = req.FormValue("stuff")
c.OtherThing = req.FormValue("otherthing")
}
This works fine till I try and parse the array.
When I do something along the lines of c.Captions = req.ParseForm("captions")
I get the error
.cannot use req.Request.ParseForm("captions") (type error) as type []ArrayText in assignment
You're doing it right, except for the assignment. When you run req.Request.ParseForm(), rather than returning a value, or passing in a reference to a buffer, it populates the req.Request.Form and req.Request.PostForm structures.
The related GoDoc explaining said function
So rather than
c.Captions = req.Request.ParseForm()
It would look more like
err := req.Request.ParseForm()
//check for errors as usual here
c.Captions = req.Request.Form
//or
c.Captions = req.Request.PostForm
Approaching it from this direction should put you on the right track.
Cheers!
Taylor

Functionality of Beego syntax 'Ctx.Input.GetData('<variable-name>')'

I am new to beego and goLang. I came across a code. If someone could explain the flow it would be very helpful. It is a GET API. I think Prepare() is like a filter. What I don't understand is c.Ctx.Input.GetData("customerid") and c.Ctx.Input.GetData("customergroupid") functions. Can someone explain me what GetData is doing and how we can pass values to them?
// URLMapping ...
func (c *CampusHomeController) URLMapping() {
c.Mapping("GetOne", c.GetOne)
}
func (c *CampusHomeController) Prepare() {
if c.Ctx.Input.GetData("customerid") == "" {
returnJSON := postCampusHomeJSON{}
returnJSON.Code = 403
returnJSON.Msg = "Invalid Session"
c.Data["json"] = &returnJSON
c.ServeJSON()
c.StopRun()
}
if c.Ctx.Input.GetData("customergroupid") == "" ||
c.Ctx.Input.GetData("customergroupid") == nil {
returnJSON := postCampusHomeJSON{}
returnJSON.Code = 404
returnJSON.Msg = "User not a campus manager"
c.Data["json"] = &returnJSON
c.ServeJSON()
c.StopRun()
}
}
GetData is used to get data from filters in your controllers. It allows you to pass values other than just strings.
From the Beego documentation:
GetData
Get value of Data in Input
SetData
Set value of Data in Input. GetData and SetData is used to pass data from Filter to Controller
https://beego.me/docs/module/context.md

Issues with Contentful SDK code after migration

See the code below I am having issues with. I have added most of the function even tho I am only getting the error in line 3. Just to give a better understanding of what I am trying to do.
func getTopArticles(_ vc: ArticleListViewController, subCatId: String) {
var articleDict = [String: Article]()
Constants.CLIENT.fetchEntries(["content_type":Constants.CONTENT_TYPE_ARTICLE,
"fields.top10Listing.sys.id":subCatId, "order":Constants.SORT_CREATED_AT_DESCENDING]) { //Getting error here
switch $0 {
case let .success(articleResult):
if articleResult.items.isEmpty {
vc.noTopArticlePresent()
}
else{
for articleEntry in articleResult.items {
let article = Article (entry:articleEntry)
vc.art.append(article)
// store into search cache
Constants.ARTICLE_CACHE.fetch(key: "articles").onSuccess({ (result) in
if let dictValue = result as? [String:Article]
{
articleDict = dictValue
articleDict[article.articleId] = article
}
Constants.ARTICLE_CACHE.set(value: articleDict, key: "articles")
}).onFailure({ (error) in
Constants.ARTICLE_CACHE.set(value: articleDict, key: "articles")
})
}
Constants.CACHE.set(value: NSKeyedArchiver.archivedData(withRootObject: vc.art), key: subCatId)
DispatchQueue.main.async {
vc.dothis()
}
}
}
}
Getting error in line 3. See error below
Argument labels '(__:,_:)' do not match any available overloads
you are missing the argument label matching for the method call.
The function signature is fetchEntries(matching:completion)
Taking your example above, and adding the our call would look like the following:
Constants.CLIENT.fetchEntries(matching:
["content_type": Constants.CONTENT_TYPE_ARTICLE,
"fields.top10Listing.sys.id":subCatId, "order":Constants.SORT_CREATED_AT_DESCENDING]) { (result: Result<ArrayResponse<Entry>>) in // Or anonymous argument $0 as you were using in your example.
Generally, if you see an error telling you argument labels don't match, you can find the declaration in the source and compare to see if you have a mismatch with the naming of your arguments being passed in. See more about argument labels and parameter names in Swift here.

How to write inresponse in indesign scripts

I am running this script for getting all form fields of a indd file.
var _ALL_FIELDS = "";
var allFields = myDocument.formFields;
for(var i=0;i<allFields.length;i++){
var tf = allFields[i];
alert(tf.id);
alert(tf.label);
alert(tf.name);
alert(_ALL_FIELDS = _ALL_FIELDS +\",\"+ tf.name);
}
What i have done is, created a soap-java based client and calling the runscript method.
Now i am able to get these fields but how to send these fields back to the client i.e. how to write this in response and then at client side how to read it from response.
Code for calling runscript method is:-
Service inDesignService = new ServiceLocator();
ServicePortType inDesignServer = inDesignService.getService(new URL(parsedArgs.getHost()));
IntHolder errorNumber = new IntHolder(0);
StringHolder errorString = new StringHolder();
DataHolder results = new DataHolder();
inDesignServer.runScript(runScriptParams, errorNumber, errorString, results);
Also I have found in docs that runScript method returns RunScriptResponse but in my case it's returning void.
http://wwwimages.adobe.com/content/dam/Adobe/en/devnet/indesign/sdk/cs6/server/ids-solutions.pdf
It looks like you want to return an array of formField names. You could take advantage of the everyItem() collection interface method in your javascript:
var result = myDocument.formFields.everyItem().name;
result;
The javascript will return the last value in the called script, so just to make it completely obvious, the last line is just the value to be returned.
On the Java side, the runScript method is passing the results variable as the 4th parameter, and that's where you'll find your response. So, after your code snippet, you might have something like this:
List<String> formFieldNames = new ArrayList<String>();
if (results.value.getData() != null) {
Data[] resultsArray = (Data[]) results.value.getData();
for (int i = 0; i < resultsArray.length; i++) {
formFieldNames.add(resultsArray[i].getData().toString());
}
}

Resources