golang learning adventure part 1.

xuanbao · · 502 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Just started golang and will try to compound my questions by the end of the week. </p> <p>I have <a href="https://pastebin.com/8BBaccdb" rel="nofollow">this</a> a basic skeleton code from net where clients can connect to it and it will echo/copy what they send. </p> <p>How can I do the following: </p> <p>1) create a config file in the same dir where there&#39;s a field <code>port:</code> i will then parse it and the program will run on that specific port instead of having me hardcoding it.</p> <p>2) How can I limit the number of connections?</p> <hr/>**评论:**<br/><br/>LadyDascalie: <pre><p>Limit connections in what way? As in max number of connections per second?</p> <p>If so, you&#39;re looking at implementing a basic rate limiter.</p> <p>There is a trivial but good learning example here: <a href="https://gobyexample.com/rate-limiting" rel="nofollow">https://gobyexample.com/rate-limiting</a></p> <p>For config files, depends what you prefer doing.</p> <p>In my case, I use the excellent <a href="https://github.com/joho/godotenv" rel="nofollow">godotenv</a> with a <code>.env</code> file at the root of my project.</p> <p>I then use <code>os.Getenv()</code> to fetch the value, as suggested previously</p></pre>juniorsysadmin1: <pre><p>The actual number of connection. So if I run the code right now, my other machines can <code>telnet $hostname $port</code>. If i limit the connection to 1 for example. My first machine can do the telnet but other will get the connection refuse until my first machine abort the connection.</p></pre>LadyDascalie: <pre><p>just use a global <code>var active bool</code> that you check against when a new connection comes in?</p> <p>If <code>active</code> is false accept the connection, otherwise bail.</p></pre>juniorsysadmin1: <pre><p>that method will only limit my code to have one connection. My ultimate idea is to have a config file specify the port, max num of connection, rate etc... have my code parse it and act accordingly. Just like a system software. </p></pre>LadyDascalie: <pre><p>Then simply increment the connections on a counter variable and define a maxConnections that gets loaded from your configuration file. You can even set it to a default value if no value is set on the config file. I’d do all this in the init function!</p></pre>smbkr: <pre><p>Instead of a config file, you might use <a href="https://golang.org/src/os/env.go" rel="nofollow">os.Getenv()</a></p></pre>allhatenocattle: <pre><p>For 1 - You could also use a flag with a default value</p> <pre><code>port := flag.String(&#34;p&#34;,&#34;2000&#34;,&#34;port to listen on&#34;) flag.Parse() startsocket(&#34;:&#34; + *port ) </code></pre> <p>For 2 - you&#39;d need to stop and start the listener once the current connections reached/went below the limit. it would be a bit simpler (and easier to troubleshoot) to always accept connections, but return an error message and close the connection immediately if you are over the high-water mark.</p></pre>allhatenocattle: <pre><p>Here is an example of sending an error message and closing the connection when you are at the conn limit: <a href="https://play.golang.org/p/vMk3YbnCay" rel="nofollow">https://play.golang.org/p/vMk3YbnCay</a></p></pre>juniorsysadmin1: <pre><p>the above is exactly what I wish to do. I got a few questions. </p> <p>1) why the function echo need to take <code>count *int64</code> as one of the argument. Isn&#39;t the count the maximum number of connection? if so why does that functions need that parameter? </p> <p>2) Inside the echo function why do you need <code>c.Close()</code>? Is that even neccesary? the closing of the connection is either the program stops, or the machine that&#39;s connected to it stopped, or there&#39;s more than the maximum number of connection have reached which is handled by the c.Close() in <code>overLimit</code>&#39;s c.Close() clause. </p></pre>allhatenocattle: <pre><p>1) echo&#39;s count parameter is the number of current connections (limit passed to overLimit is the max number of connections). It gets passed as a *int64 so the atomic.AddInt64 can be used to correctly modify the value when multiple goroutines may be accessing it at once. Slightly modified var names to make it clearer: <a href="https://play.golang.org/p/6tkojLh_W-" rel="nofollow">https://play.golang.org/p/6tkojLh_W-</a></p> <p>2) It is good practice to close resources when they are not needed. In trivial programs it might not matter, but get in the habit so you won&#39;t be troubleshooting resource leaks as the programs get more complicated. </p></pre>juniorsysadmin1: <pre><p>Why did you declare your variables via flag and pass in the pointers explicitly? Is there some best practice reason behind it? This is how I do it <a href="https://play.golang.org/p/1Khq7jXBr5" rel="nofollow">currently</a></p></pre>allhatenocattle: <pre><p>When using the flag package, you can either use flag.Int() /flag.String() and get back pointers, or declare vars ahead of time and use flag.IntVar()/flag.StringVar().</p> <p>I chose the simpler method and passed the pointer in since it was less lines than declaring the vars ahead of time.</p> <p>I&#39;m not a fan of the readconfig func, it doesn&#39;t have defaults and doesn&#39;t give a helpful message if the values aren&#39;t there. Using the flag package you get output like the following if you pass -h:</p> <pre><code>Usage of ./yourprogram: </code></pre> <p>-a string listen addr (default &#34;127.0.0.1:2000&#34;) -c int max connections (default 1)</p> <p>For programs that have a bunch of options, I&#39;ll typically switch to using a configuration file.</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

502 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传