GoLang put string in map - string

So, I'm trying to add a string to an existing map that is created from toml.
http://hastebin.com/vayolavose
When I try and build I get the error:
./web.go:56: arguments to copy have different element types: []proxy.Address and string
How would I go about converting it? I've been trying this for the past like 4 hours.
Thanks

while,the code below is your source code
func handleAddFunc(w http.ResponseWriter, r *http.Request) {
backend := r.FormValue("backend")
key := r.FormValue("key")
if !isAuthorized(key) {
respond(w, r, 403, "")
return
}
w.Header().Set("Content-Type", "text/plain")
if !readConfig() {
return
}
activeAddrs = make([]proxy.Address, len(config.Proxy.ServerAddrs))
backendAddr = make([]proxy.Address, len(backend))
copy(backendAddr, config.Proxy.ServerAddrs)
copy(backendAddr, backend)
loadBalancer.SetAddrs(backendAddr)
fmt.Fprintf(w, "Input value of ", backend, "and here is the byte", backendAddr)
}
your code's error, is copy(backendAddr, backend), variable backend is a string value from the request from, you may change this into []proxy.Address, such as (consider I donnot know the struct of proxy.Address ):
var backendAddr = []proxy.Address{}
for _,str := range strings.split(backend,","){
backendAddr = append(backendAddr, &proxy.Address(str))
}

Related

Reading Redis key-value which is JSON string using redigo

I am trying to read Redis Key-val in Go. Key is string and value is JSON string. Eg- Key=
discov_32161296
and Value as Json string=
"{\"10283\":true,\"11064\":true,\"15123\":true,\"15447\":true,\"15926\":true,\"16530\":true,\"16537\":true,\"16799\":true,\"17088\":true,\"17249\":true,\"18501\":true,\"18529\":true,\"18601\":true,\"3044\":true,\"3687\":true,\"4926\":true,\"5483\":true,\"6\":true,\"6675\":true,\"8332\":true,\"8336\":true,\"8674\":true}"
Getting below error while reading in Go
redis.Values err redigo: unexpected type for Values, got type []uint8
Here's my code :
uIDDiscoveryOffer := fmt.Sprintf("%s_%d", "discov", uid)
opDataStr, err := redis.String(redis.Values(con.Do("GET", uIDDiscoveryOffer)))
if err != nil || err != redis.ErrNil {
utils.Log1("readCacheTxnByUID-Disc-redis.Values-err", fmt.Sprint("redis.Values err : ", uidDiscoveryOffer, " error: ", err.Error()))
} else {
//Some Logic
}
The Redis GET returns the value of a key. redis.Values() may be used to convert the result of a command that returns multiple items.
Since GET returns a single item, only use redis.String(), you don't need redis.Values() here:
opDataStr, err := redis.String(con.Do("GET", uIDDiscoveryOffer))

Remove all characters after a delimiter in a string

I am building a web crawler application in golang.
After downloading the HTML of a page, I separate out the URLs.
I am presented with URLs that have "#s" in them, such as "en.wikipedia.org/wiki/Race_condition#Computing". I would like to get rid of all characters following the "#", since these lead to the same page anyways. Any advice for how to do so?
Use the url package:
u, _ := url.Parse("SOME_URL_HERE")
u.Fragment = ""
return u.String()
An improvement on the answer by Luke Joshua Park is to parse the URL relative to the URL of the source page. This creates an absolute URL from what might be relative URL on the page (scheme not specified, host not specified, relative path). Another improvement is to check and handle errors.
func clean(pageURL, linkURL string) (string, error) {
p, err := url.Parse(pageURL)
if err != nil {
return "", err
}
l, err := p.Parse(linkURL)
if err != nil {
return "", err
}
l.Fragment = "" // chop off the fragment
return l.String()
}
If you are not interested in getting an absolute URL, then chop off everything after the #. This works because the only valid use of # in a URL is the fragment separator.
func clean(linkURL string) string {
i := strings.LastIndexByte(linkURL, '#')
if i < 0 {
return linkURL
}
return linkURL[:i]
}

Hyperledger Fabric golang chaincode not working as expected store data on ledger manually but not when try to store via function call

i am trying to store fund transfer record on hyperledger fabric. i have written chain code in go lang. it work fine when i add data in initLedger function. but when i call it from other function like createTransfer(i will provide both codes) it show successful transaction but when i retrieve chain data .it does not appear in it.
transfer struct
type Transfer struct {
TransferID string `json:"transferID"`
FromAccount string `json:"fromAccount"`
ToAccount string `json:"toAcount"`
Amount string `json:"amount"`
}
this function write data to ledger: it workis fine when i directly call it in initLedger method
func writeTransferToLedger(APIStub shim.ChaincodeStubInterface, transfers []Transfer) sc.Response {
for i := 0; i < len(transfers); i++ {
key := transfers[i].TransferID
chkBytes, _ := APIStub.GetState(key)
if chkBytes == nil {
asBytes, _ := json.Marshal(transfers[i])
err := APIStub.PutState(transfers[i].TransferID, asBytes)
if err != nil {
return shim.Error(err.Error())
}
} else {
msg := "Transfer already exist" + key + " Failure---------------"
return shim.Error(msg)
}
}
return shim.Success([]byte("Write to Ledger"))
}
Call writeToTransferLedger method with in createTransfer function:
func (s *SmartContract) createTransfer(APIStub shim.ChaincodeStubInterface, args []string) sc.Response {
if len(args) != 4 {
return shim.Error("Incorrect Number of arguments for transfer func, Expecting 4")
}
transfers := []Transfer{Transfer{TransferID: args[0], FromAccount: args[1], ToAccount: args[2], Amount: args[3]}}
writeTransferToLedger(APIStub, transfers)
return shim.Success([]byte("stored:" + args[0] + args[1] + args[2] + args[3]))
}
when i call createTransfer from nodesdk code it execute succefully but when i retrive data from chain code not thing return.
i Expect it to work with createTransfer function as it is working with writeTransferToLedger.
inside initLedger method i have created transfer struct with given data and called writeTransferToLedger function code is given below:
transfer := []Transfer{
{TransferID: "1233", FromAccount: "US_John_Doe_123", ToAccount: "UK_Alice_456", Amount: "200"},
{TransferID: "231", FromAccount: "JPY_Alice_456", ToAccount: "UK_John_Doe", Amount: "3000"},
}
writeTransferToLedger(APIstub, transfer)
thanks for your help . i have resolved the issue.
i was calling invoke function when trying to retrieve data from customer ledger.
i have to query the ledger and get transfer data from ledger.

Insert a mgo query []M.bson result into a file.txt as a string

i have to insert into a file the result of a mgo query MongoDB converted in Go to get the id of images
var path="/home/Medo/text.txt"
pipe := cc.Pipe([]bson.M{
{"$unwind": "$images"},
{"$group": bson.M{"_id": "null", "images":bson.M{"$push": "$images"}}},
{"$project": bson.M{"_id": 0}}})
response := []bson.M{}
errResponse := pipe.All(&response)
if errResponse != nil {
fmt.Println("error Response: ",errResponse)
}
fmt.Println(response) // to print for making sure that it is working
data, err := bson.Marshal(&response)
s:=string(data)
if err22 != nil {
fmt.Println("error insertion ", err22)
}
Here is the part where I have to create a file and write on it.
The problem is when I got the result of the query in the text file I got an enumeration values in the last of each value for example:
id of images
23456678`0`
24578689`1`
23678654`2`
12890762`3`
76543890`4`
64744848`5`
so for each value i got a number sorted in the last , and i can't figure out how , after getting the reponse from the query i converted the Bson to []Byte and then to Stringbut it keeps me getting that enumeration sorted values in the last of each results
I'd like to drop those 0 1 2 3 4 5
var _, errExistFile = os.Stat(path)
if os.IsNotExist(errExistFile) {
var file, errCreateFile = os.Create(path)
if isError(erro) {
return
}
defer file.Close()
}
fmt.Println("==> done creating file", path)
var file, errii = os.OpenFile(path, os.O_RDWR, 0644)
if isError(errii) {
return
}
defer file.Close()
// write some text line-by-line to file
_, erri := file.WriteString(s)
if isError(erri) {
return
}
erri = file.Sync()
if isError(erri) {
return
}
fmt.Println("==> done writing to file")
You could declare a simple struct eg
simple struct {
ID idtype `bson:"_id"`
Image int `bson:"images"`
}
The function to put the image ids into the file would be
open file stuff…
result := simple{}
iter := collection.Find(nil).Iter()
for iter.Next(&result){
file.WriteString(fmt.Sprintf("%d\n",result.Image))
}
iter.Close()

Golang : type conversion between slices of structs

This questions follows another question of mine.
I don't exactly get what is wrong with my attempt to convert res to a ListSociete in the following test code :
import (
"errors"
"fmt"
"github.com/jmcvetta/neoism"
)
type Societe struct {
Name string
}
type ListSociete []Societe
func loadListSociete(name string) (ListSociete, error) {
db, err := neoism.Connect("http://localhost:7474/db/data")
if err != nil {
return nil, err
}
res := []struct {
Name string `json:"a.name"`
}{}
cq := neoism.CypherQuery{
Statement: `
MATCH (a:Societe)
WHERE a.name = {name}
RETURN a.name
`,
Parameters: neoism.Props{"name": name},
Result: &res,
}
db.Cypher(&cq)
if len(res) == 0 {
return nil, errors.New("Page duz not exists")
}
r := res[0]
return ListSociete(res), nil
}
Is a []struct{Name string} different from a []struct{Name string json:"a.name" } ?
Or is a ListSociete different from a []struct{Name string} ?
Thanks.
You are currently dealing with two different types:
type Societe struct {
Name string
}
and the anonymous one:
struct {
Name string `json:"a.name"`
}
These two would be identical if it wasn't for the tag. The Go Specifications states (my emphasis):
Two struct types are identical if they have the same sequence of fields, and if
corresponding fields have the same names, and identical types, and identical tags.
Two anonymous fields are considered to have the same name. Lower-case field names
from different packages are always different.
So, you can't do a simple conversion between the two. Also, the fact that you are converting slices of the two types makes the conversion problematic. I can see two options for you:
Copy through iteration:
This is the safe and recommended solution, but it is also more verbose and slow.
ls := make(ListSociete, len(res))
for i := 0; i < len(res); i++ {
ls[i].Name = res[i].Name
}
return ls, nil
Unsafe conversion:
Since both types have the same underlying data structure, it is possible to do an unsafe conversion.
This might however blow up in your face later on. Be warned!
return *(*ListSociete)(unsafe.Pointer(&res)), nil
Playground Example: http://play.golang.org/p/lfk7qBp2Gb
So, after some tests, here's whats i found out :
A ListSociete defined as such...
type Societe struct {
Name string `json:"a.name"`
}
type ListSociete []Societe
is different from this :
type ListSociete []struct {
Name string `json:"a.name"`
}
This second solution works, whereas the first doesn't.
So I assume there really is no way to convert (directly without writing an explicit loop) between types with different tags ?
In that case, i'll definitely go with the loop, as using tags directly in types (cf. second solution above) would make my code unreadable and unreusable, also I really have no clue what I would be messing with using the unsafe conversion method. So thanks for confirming different tags made different types.

Resources