José Colón | 3 Sep 16:11 2015
Picon

"for select {}" statement?

Maybe this is naive, but I see the use of select statements inside infinite for loops over and over, and it's a really useful construct. I thus wonder if the language could have a "for select" statement.

for select {
  case c <- 1:
  case c <- 0:
}

instead of 

for {
  select {
    case c <- 1:
    case c <- 0:
  }
}

I know it's just saving us from typing two curly braces, but it may make code cleaner?

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org.
For more options, visit https://groups.google.com/d/optout.
Sebastien Binet | 3 Sep 14:41 2015
Picon

[gomobile] bind/seq implementation for cpython VM

hi there,

with the rules being defined over there
https://github.com/golang/go/issues/12416 I will have to revise the
mechanism I used for the generation of CPython extension modules with
my `gopy` command.
Namely, I think I'll use the x/mobile/bind/seq
serialization/procedure-call protocol.

I can of course just cherry pick some parts of the android backend of
bind and start from there (and run with it) but I was wondering if a
standalone C-library (in x/mobile/somewhere) wouldn't also fit the
bill.

any thoughts?

-s

--

-- 
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@...
For more options, visit https://groups.google.com/d/optout.

WALID BELRHALMIA | 3 Sep 14:21 2015
Picon

Buffered function of bufio package

a wired question : about this function 

func (b *Reader) Buffered() int

normally this function return the size of the buffer

And look now to this code : 

file, err := os.Open("fuck.text")
 bufferedReader
:= bufio.NewReader(file)
 fmt
.Println(bufferedReader.Buffered())

normally the size of the buffer most be the defaukt size 4096 bytes but i Buffered function return me 0 .


--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org.
For more options, visit https://groups.google.com/d/optout.
sajal83 | 3 Sep 12:17 2015
Picon

How to get DNS lookup time from Dialer.Dial ?

Hi,

I am using Dialer.Dial from package net to make a tcp connection. Currently i can measure the time it takes to make the connection like so :-

 start := time.Now()
 dialer
:= &net.Dialer{ }
 con
, err := dialer.Dial("tcp", "example.com:80")
 log
.Println("dial time: ", time.since(start))


This gives me the total time to establish the connection which includes DNS and tcp connect. I would like to know the DNS lookup time and connect time separately...

So far the options I see are...

1. Resolve the hostname by hand, and feed one of the ip into Dial - but here I loose fallback and dualstack strategy provided inside Dialer.Dial
2. Recreate the whole logic in my code - But this is too much work and I am lazy. Reproducing things from standard library sounds like not a good thing.

The first thing Dialer.Dial ( https://golang.org/src/net/dial.go?s=6061:6121#L197 ) does is :-

 addrs, err := resolveAddrList("dial", network, address, finalDeadline)


Is there a way to either time that step? Or be able to provide a list of addrs to Dial instead of single IP?

Looking for an easier way out.

PS: My code where I need to implement this : https://github.com/turbobytes/pulse/blob/master/utils/curl.go#L77 inside func dial 

-Sajal

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org.
For more options, visit https://groups.google.com/d/optout.
Andy G. | 3 Sep 09:42 2015
Picon

An (official) interface for net/http: http.Client ?

Hey gophers,

in the last time i often use golang with a combination of HTTP / REST APIs.
Often the net/http package and even more the http.Client [1] / http.DefaultClient is involved.

Sadly i can`t find an official interface for this client in the standard library.
Of course i can create one myself, but i think it make sense to put something like this in the standard library.
Is there one interface i can`t find?
And if not is there a reason why there is no?

I just try to understand this.

Why i think it is useful:
When your program / package will be bigger and bigger you try to decouple from concrete implementations.
To offer the user the most flexibility.
Of course you can do something like this (seen in [2]):

func NewClient(httpClient *http.Client) *Client {
if httpClient == nil {
httpClient = http.DefaultClient
}
c := &Client{client: httpClient}
return c
}
But with an interface it would be much more easier to mock httpClient for unit testing or wrapping things for middle ware contextes.
Or am i wrong?

Thanks and have a nice day,
Andy

[1] http://golang.org/pkg/net/http/#Client
[2] https://github.com/google/go-github/blob/master/github/github.go#L128

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org.
For more options, visit https://groups.google.com/d/optout.
daniel | 3 Sep 06:39 2015

[gomobile] Global Const

Does gomobile support a package that has public global const? I'm getting a ton of these errors:

not yet supported, name for const github.com/me/somepackage.GLOBAL_VAR untyped string / *types.Const


Seems very difficult to get anything to compile to a framework here due to the limited type system.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org.
For more options, visit https://groups.google.com/d/optout.
Dump Hole | 3 Sep 06:16 2015
Picon

1K TCP connection limit?

I am trying to debug an issue with my TCP server that it seems it's only able to accept 1K connections, and after that it can't accept more and disconnects all connections, and starts going into this weird state.

I wrote a small app (another Go app) that spawns clients and connects to the server running on localhost.  Everything goes well if the number of clients are < 1K.  However, once I bumped it up, it starts failing right around 1020, which is suspiciously close to 1024.  I need to know if it's my code, which seems more likely, or some weird bug with Go TCP, but at this point my code hasn't done anything yet.

This is the simplified version of my TCP server:
http://play.golang.org/p/_EJ9oNZ0Cv

It's very simple.  It listens to a port, new connection comes in, store the net.TCPConn object in an array.

I wrote another go program that spawns clients
http://play.golang.org/p/fsEirFIUqR

Now, run the server, run the clients, and notice connections will start failing around 1020.

Could somebody please explain why this is the case?

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org.
For more options, visit https://groups.google.com/d/optout.
Gyu-Ho Lee | 3 Sep 05:42 2015
Picon

Any easier way to share states between handlers with net.context.Context?

Hello,

The article explains:

At Google, we developed a context package that makes it easy to pass request-scoped values,
cancelation signals, and deadlines across API boundaries to all the goroutines involved in handling
a request. The package is publicly available as golang.org/x/net/context.


It says it is limited within a request.  Then what if I want to share variables between requests?
How would you do without defining global variables? Is using context for this a good idea?

In my code, I have two handlers with one shared context.
One handler updates its context, and another handler reads from the text values.
When the handler updates the context values, I was expecting to see it propagated to
the other handler, but it does not.

Here's the output:
/*
http://localhost:8080
Root = AppStartTS:  / IP: <nil> / UserAgent:

http://localhost:8080/set
Set = AppStartTS: 2015-09-02 20:19:42.430449518 -0700 PDT / IP: 127.0.0.1 / UserAgent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36
*/


- "/" is the endpoint that reads from context.
- "/set" is the endpoint that updates the context values.

Those two handlers receive the same context but do not sync in my code.
I can try passing pointers of context but context is an interface, so I think I shouldn't.


Is there any easier way to share values between handlers using context, without using global variables?

Thanks!






Here's a full working code:

package main

import (
"encoding/json"
"fmt"
"net"
"net/http"
"time"

"golang.org/x/net/context"
)

type ContextHandler interface {
ServeHTTPContext(context.Context, http.ResponseWriter, *http.Request) error
}

type ContextHandlerFunc func(context.Context, http.ResponseWriter, *http.Request) error

func (f ContextHandlerFunc) ServeHTTPContext(ctx context.Context, w http.ResponseWriter, req *http.Request) error {
return f(ctx, w, req)
}

type ContextAdapter struct {
ctx     context.Context
handler ContextHandler // to wrap func(context.Context, ResponseWriter, *Request) error
}

func (ca *ContextAdapter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if err := ca.handler.ServeHTTPContext(ca.ctx, w, req); err != nil {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{
"status":  "error",
"message": err.Error(),
})
}
}

func NewRootContext(ts string) context.Context {
return context.WithValue(context.Background(), appStartTSKey, ts)
}

func main() {
rootContext := context.Background()
mainRouter := http.NewServeMux()
mainRouter.Handle("/", &ContextAdapter{
ctx:     rootContext,
handler: ContextHandlerFunc(handlerRoot),
})
mainRouter.Handle("/set", &ContextAdapter{
ctx:     rootContext,
handler: ContextHandlerFunc(handlerSet),
})

port := ":8080"
fmt.Println("Serving http://localhost" + port)
if err := http.ListenAndServe(port, mainRouter); err != nil {
panic(err)
}
}

func handlerRoot(ctx context.Context, w http.ResponseWriter, req *http.Request) error {
switch req.Method {
case "GET":
fmt.Println("handlerRoot")
ts, _ := getAppStartTSFromContext(ctx)
ip, _ := getIPFromContext(ctx)
ua, _ := getUserAgentFromContext(ctx)
fmt.Fprintf(w, "Root = AppStartTS: %s / IP: %v / UserAgent: %s", ts, ip, ua)
return nil

default:
http.Error(w, "Method Not Allowed", 405)
return fmt.Errorf("Method Not Allowed:", req.Method)
}
}

func handlerSet(ctx context.Context, w http.ResponseWriter, req *http.Request) error {
switch req.Method {
case "GET":
fmt.Println("handlerSet")
ts := time.Now().String()
ip, err := getIP(req)
if err != nil {
return err
}
ua := req.UserAgent()
ctx = setContextWithAppStartTS(ctx, ts)
ctx = setContextWithIP(ctx, ip)
ctx = setContextWithUserAgent(ctx, ua)
fmt.Fprintf(w, "Set = AppStartTS: %s / IP: %v / UserAgent: %s", ts, ip, ua)
return nil

default:
http.Error(w, "Method Not Allowed", 405)
return fmt.Errorf("Method Not Allowed:", req.Method)
}
}

type key int

const appStartTSKey key = 0

const userIPKey key = 1

const userAgentKey key = 2

func setContextWithAppStartTS(ctx context.Context, ts string) context.Context {
return context.WithValue(ctx, appStartTSKey, ts)
}

func setContextWithIP(ctx context.Context, userIP net.IP) context.Context {
return context.WithValue(ctx, userIPKey, userIP)
}

func setContextWithUserAgent(ctx context.Context, userAgent string) context.Context {
return context.WithValue(ctx, userAgentKey, userAgent)
}

func getAppStartTSFromContext(ctx context.Context) (string, bool) {
// ctx.Value returns nil if ctx has no value for the key;
// the string type assertion returns ok=false for nil.
ts, ok := ctx.Value(appStartTSKey).(string)
return ts, ok
}

func getIPFromContext(ctx context.Context) (net.IP, bool) {
userIP, ok := ctx.Value(userIPKey).(net.IP)
return userIP, ok
}

func getUserAgentFromContext(ctx context.Context) (string, bool) {
userAgent, ok := ctx.Value(userAgentKey).(string)
return userAgent, ok
}

// getIP extracts the user IP address from req, if present.
// https://blog.golang.org/context/userip/userip.go
func getIP(req *http.Request) (net.IP, error) {
ip, _, err := net.SplitHostPort(req.RemoteAddr)
if err != nil {
return nil, fmt.Errorf("userip: %q is not IP:port", req.RemoteAddr)
}
userIP := net.ParseIP(ip)
if userIP == nil {
return nil, fmt.Errorf("userip: %q is not IP:port", req.RemoteAddr)
}
return userIP, nil
}

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org.
For more options, visit https://groups.google.com/d/optout.
WALID BELRHALMIA | 3 Sep 04:58 2015
Picon

buffer size and file size

Imagine that we create a new reader from the bufio package . From a file of 4 gb than the buffer of this reader
will contain only a porsion of this file , so we can't read all the file. But i test it and it work how that happen

--

-- 
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@...
For more options, visit https://groups.google.com/d/optout.
Daniel Lochrie | 3 Sep 03:42 2015
Picon

OAuth2 URL Deprecation and Preferred Client Strategy

I have an application that is using OAuth2 for user authentication, and while it is working for both Google and Facebook (should be trivial to add other providers at any time), I had some questions about the actual preferred way of handling the request for the authenticated user's data. I have posted a sample of my code (Note: I am using App Engine for this application):

// ...logic...

// Since we are using App Engine, we MUST pass in an App Engine
// context as opposed to the "oauth2.NoContext" context.
context
:= appengine.NewContext(req)

// Get the authentication token for this login.
token
, err := providerConf.Exchange(context, authcode)
if err != nil {
 
HandleError(res, req, &appError{err, "There was a system error.", 500})
 
return
}

var profileUrl string
switch providerName {
case "facebook":
  profileUrl
= "https://graph.facebook.com/me?access_token="
case "google":
  profileUrl
= "https://www.googleapis.com/oauth2/v2/userinfo?access_token="
}

// In App Engine, "urlfetch" must be used for inbound and outbound requests.
client
:= urlfetch.Client(context)
response
, err := client.Get(profileUrl + token.AccessToken)
if err != nil {
 
HandleError(res, req, &appError{err, "There was a system error.", 500})
 
return
}

// Read the raw response body so we can serialize it.
// ...logic...

The first question I had is what Google URL should I use to fetch a user's profile data? The one I have been using is https://www.googleapis.com/oauth2/v2/userinfo?access_token=tokenHashHere. When I read about OAuth2 in general, I find that for Google the docs say to use https://www.googleapis.com/oauth2/v3/token, as detailed here. The first URL does the job for me, but it is a GET request, in contrast to the second URL which requires a POST. I've also read that the GET endpoint is being deprecated, as mentioned in the SO answer. So I guess the question is, what URL should we use, and should we be doing POSTs instead of GETs? If it is a POST, should we be using use it for all the other providers as well?

...

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org.
For more options, visit https://groups.google.com/d/optout.
Vasko Zdravevski | 3 Sep 02:25 2015
Picon

runtime.LockOSThread question

Hi Gophers,

The docs for http://golang.org/pkg/runtime/#LockOSThread read as follows:
LockOSThread wires the calling goroutine to its current operating system thread. Until the calling goroutine exits or calls UnlockOSThread, it will always execute in that thread, and no other goroutine can.
I'm curious about the fragment I highlighted ... "and no other goroutine can" what? Can run in that thread? (Probably not the case with GOMAXPROCS=1) Maybe "no other goroutine can call LockOSThread on the same thread"?

So I searched "golang-nuts" and I found an older question on this, but the answer doesn't appear to be what I'm observing: https://groups.google.com/forum/#!searchin/golang-nuts/LockOSThread/golang-nuts/XFlbZ5_y1_k/48yjdI5zLM0J

Whatever the answer is, what I'm trying to find is a way to dedicate a thread to avoid situations where CPU intensive threads that don't perform blocking calls regularly don't hog the threads because of cooperative scheduler.

Here is an example: http://play.golang.org/p/tOyDjgxKYq

I thought 'LockOSThread' would guarantee my goroutine a thread to run that other goroutines couldn't hog, but apparently not the case. Any ideas on how to do that aside from the approach or guaranteeing that goroutines give up threads in reasonable intervals?

Env details:
go version devel +df37c4b Wed Sep 2 20:24:40 2015 +0000 darwin/amd64
GOMAXPROCS=NumCPU=8

Thanks,
Vasko.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org.
For more options, visit https://groups.google.com/d/optout.

Gmane