<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Suman Chapai on Medium]]></title>
        <description><![CDATA[Stories by Suman Chapai on Medium]]></description>
        <link>https://medium.com/@sumanchapai?source=rss-4763fe70368b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*O9C-gRXa2qHPKpR-tb6cLw.jpeg</url>
            <title>Stories by Suman Chapai on Medium</title>
            <link>https://medium.com/@sumanchapai?source=rss-4763fe70368b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 07:50:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sumanchapai/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Redoing git mergetool using vimdiff]]></title>
            <link>https://medium.com/@sumanchapai/redoing-git-mergetool-using-vimdiff-9ae0a4d12af5?source=rss-4763fe70368b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ae0a4d12af5</guid>
            <category><![CDATA[vim]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Suman Chapai]]></dc:creator>
            <pubDate>Fri, 14 Jun 2024 12:09:01 GMT</pubDate>
            <atom:updated>2024-06-14T12:09:43.811Z</atom:updated>
            <content:encoded><![CDATA[<p>When you save and exit out of files in vimdiff, git thinks that you’ve resolved the conflicts. If you haven’t, you can tell git so using</p><p>git update-index --unresolve file-thats-not-resolved.txt</p><p>Then you can open vimdiff (or any other merge tool you are using) again using git mergetool</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ae0a4d12af5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JSON prettify command line pipe]]></title>
            <link>https://medium.com/@sumanchapai/json-prettify-command-line-pipe-0ece06aff7a4?source=rss-4763fe70368b------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ece06aff7a4</guid>
            <dc:creator><![CDATA[Suman Chapai]]></dc:creator>
            <pubDate>Mon, 11 Mar 2024 15:39:17 GMT</pubDate>
            <atom:updated>2024-03-11T15:39:17.174Z</atom:updated>
            <content:encoded><![CDATA[<p>If you fetch JSON through curl or other cmd utlity and want to see it prettified, simply pipe your original command to python -m json.tool .</p><p>For example:</p><pre>curl -s -X GET localhost:4000/v1/movies/13<br><br>// Output<br>{&quot;ID&quot;:13,&quot;CreatedAt&quot;:&quot;2024-03-11T21:17:08.973847+05:45&quot;,&quot;Title&quot;:&quot;Casablanca&quot;,&quot;Year&quot;:0,&quot;Runtime&quot;:102,&quot;Genres&quot;:[&quot;drama&quot;,&quot;romance&quot;,&quot;war&quot;],&quot;Version&quot;:1}</pre><p>And,</p><pre>curl -s -X GET localhost:4000/v1/movies/13 | python -m json.tool<br><br>// Output<br>{<br>    &quot;ID&quot;: 13,<br>    &quot;CreatedAt&quot;: &quot;2024-03-11T21:18:37.793343+05:45&quot;,<br>    &quot;Title&quot;: &quot;Casablanca&quot;,<br>    &quot;Year&quot;: 0,<br>    &quot;Runtime&quot;: 102,<br>    &quot;Genres&quot;: [<br>        &quot;drama&quot;,<br>        &quot;romance&quot;,<br>        &quot;war&quot;<br>    ],<br>    &quot;Version&quot;: 1<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ece06aff7a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Updating major version in your go package]]></title>
            <link>https://medium.com/@sumanchapai/updating-major-version-in-your-go-package-b19847aa5493?source=rss-4763fe70368b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b19847aa5493</guid>
            <dc:creator><![CDATA[Suman Chapai]]></dc:creator>
            <pubDate>Tue, 27 Feb 2024 16:28:44 GMT</pubDate>
            <atom:updated>2024-02-27T16:28:44.676Z</atom:updated>
            <content:encoded><![CDATA[<p>If you are updating major version of your go package, you must also modify the go.mod file with the version tag. This is to address the go compatibility promise:</p><p><a href="https://go.dev/doc/modules/major-version">Developing a major version update - The Go Programming Language</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b19847aa5493" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding git files with asterisks. pattern match]]></title>
            <link>https://medium.com/@sumanchapai/adding-git-files-with-asterisks-pattern-match-13437fb4ac71?source=rss-4763fe70368b------2</link>
            <guid isPermaLink="false">https://medium.com/p/13437fb4ac71</guid>
            <dc:creator><![CDATA[Suman Chapai]]></dc:creator>
            <pubDate>Fri, 09 Feb 2024 08:07:50 GMT</pubDate>
            <atom:updated>2024-02-09T08:07:50.201Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://www.tempertemper.net/blog/adding-files-for-a-commit-with-asterisks">https://www.tempertemper.net/blog/adding-files-for-a-commit-with-asterisks</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13437fb4ac71" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[github cli — gh pager]]></title>
            <link>https://medium.com/@sumanchapai/github-cli-gh-pager-5b1372556f99?source=rss-4763fe70368b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b1372556f99</guid>
            <dc:creator><![CDATA[Suman Chapai]]></dc:creator>
            <pubDate>Wed, 07 Feb 2024 05:57:32 GMT</pubDate>
            <atom:updated>2024-02-07T05:57:32.916Z</atom:updated>
            <content:encoded><![CDATA[<h3>github cli — gh pager</h3><p>To list the current config: gh config list</p><p>A scrollable pager gh config set pager less</p><p>Normal output gh config set pager cat</p><p>Here, we’re specifying the command (less or cat) to receive the output of the gh command. This is in the UNIX spirit of command compositions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b1372556f99" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vim quickfix]]></title>
            <link>https://medium.com/@sumanchapai/vim-quickfix-a5cca3b69dbb?source=rss-4763fe70368b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5cca3b69dbb</guid>
            <category><![CDATA[vim]]></category>
            <category><![CDATA[neovim]]></category>
            <category><![CDATA[vim-quickfix]]></category>
            <dc:creator><![CDATA[Suman Chapai]]></dc:creator>
            <pubDate>Sun, 21 Jan 2024 13:06:31 GMT</pubDate>
            <atom:updated>2024-01-21T13:06:31.486Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://stackoverflow.com/questions/1747091/how-do-you-use-vims-quickfix-feature">How do you use vim&#39;s quickfix feature?</a></p><p>Pretty useful when using with telescope… select items with tab, open selected with quickfix using meta-q</p><pre>:copen &quot; Open the quickfix window<br>:ccl   &quot; Close it<br>:cw    &quot; Open it if there are &quot;errors&quot;, close it otherwise (some people prefer this)<br>:cn    &quot; Go to the next error in the window<br>:cp    &quot; Go to the previous error in the window<br>:cnf   &quot; Go to the first error in the next file<br>:.cc   &quot; Go to error under cursor (if cursor is in quickfix window)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5cca3b69dbb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Updating homebrew packages]]></title>
            <link>https://medium.com/@sumanchapai/updating-homebrew-packages-a17afccd2f34?source=rss-4763fe70368b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a17afccd2f34</guid>
            <category><![CDATA[homebrew]]></category>
            <dc:creator><![CDATA[Suman Chapai]]></dc:creator>
            <pubDate>Sun, 21 Jan 2024 04:48:54 GMT</pubDate>
            <atom:updated>2024-01-21T04:48:54.188Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>TLDR</strong>;</p><pre>brew update &amp;&amp; brew upgrade &lt;gh | yabai | pacakge of your choice&gt;</pre><p>I have always had problems updating homebrew packages. Maybe I know this now.</p><p>There are two commands in homebrew that are confusingly similar update and upgrade.</p><p>In order to get a newer version of the package you’ll first have to update homebrew by running brew update. What this does is tell homebrew to get a list of latest version of brew packages. So the next time you install a package, it will get this latest version.</p><p>After updating brew, you could upgrade your desired package to latest version using brew upgrade yabai (where yabai is to be replaced with package of your choice). Just brew upgrade upgrades all installed packages to latest version.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a17afccd2f34" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Proxy vs Reverse Proxy]]></title>
            <link>https://medium.com/@sumanchapai/proxy-vs-reverse-proxy-70529e35bd3f?source=rss-4763fe70368b------2</link>
            <guid isPermaLink="false">https://medium.com/p/70529e35bd3f</guid>
            <dc:creator><![CDATA[Suman Chapai]]></dc:creator>
            <pubDate>Tue, 05 Sep 2023 22:05:19 GMT</pubDate>
            <atom:updated>2023-09-05T22:05:19.411Z</atom:updated>
            <content:encoded><![CDATA[<p>Proxy, literally, is a “representative”, something/someone that can act on the behalf of others. In networking sense, a proxy is a server with a public IP. It’s called a proxy because it talks to the world on your behalf and on the behalf of others in your network. In that sense, it’s your representative.</p><p>A reverse proxy on the other hand is a proxy too, but it’s a proxy for the servers. For example, if you have a fleet of servers, you can only expose the reverse proxy to the world and the reverse proxy will make necessary communication on the behalf of the actual servers to the outer world.</p><p>Examples:</p><p>An organization may use a proxy to set up rules of what kind of connections users can make to the world.</p><p>A reverse proxy may be used to set up rate limiting rules, cache, or authentication only getting the response from the actual server when needed and forwarding those request to the clients.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70529e35bd3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sleek. Go]]></title>
            <link>https://medium.com/@sumanchapai/sleek-go-2243bfbe690f?source=rss-4763fe70368b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2243bfbe690f</guid>
            <dc:creator><![CDATA[Suman Chapai]]></dc:creator>
            <pubDate>Sun, 03 Sep 2023 23:22:29 GMT</pubDate>
            <atom:updated>2023-09-03T23:24:57.503Z</atom:updated>
            <content:encoded><![CDATA[<p>Go’s source code is always so sleek. This mostly comes from the Unix-y authors who like the Go authors and their relatives were mostly Electrical engineers… thus the procedural code with tricks and elegance, i suppose. Similar is Brian Kernighan’s code (relative of Go, Unix, C, etc.)</p><p>For example, I was writing the the implementation of the LimitReader function. A function that takes a reader and a max number of bytes to read and returns another reader that after reading n bytes returns EOF.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SYA0m0uacjcK_b8wmjAdyQ.png" /></figure><p>Here was my version</p><pre>type limitedReader struct {<br> innerReader io.Reader<br> read        int64<br> readLimit   int64<br>}<br><br>func LimitReader(r io.Reader, n int64) io.Reader {<br> return &amp;limitedReader{r, 0, n}<br>}<br><br>func (l *limitedReader) Read(p []byte) (int, error) {<br> if l.read &gt;= l.readLimit {<br>  return 0, io.EOF<br> }<br> remainingLimit := int(l.readLimit - l.read)<br> if len(p) &gt; remainingLimit {<br>  p = p[:remainingLimit]<br> }<br> n, err := l.innerReader.Read(p)<br> l.read += int64(n)<br> return n, err<br>}</pre><p>Then I looked at the source code of Go to see how they had done it.</p><pre>func LimitReader(r Reader, n int64) Reader { return &amp;LimitedReader{r, n} }<br><br>// A LimitedReader reads from R but limits the amount of<br>// data returned to just N bytes. Each call to Read<br>// updates N to reflect the new amount remaining.<br>// Read returns EOF when N &lt;= 0 or when the underlying R returns EOF.<br>type LimitedReader struct {<br> R Reader // underlying reader<br> N int64  // max bytes remaining<br>}<br><br>func (l *LimitedReader) Read(p []byte) (n int, err error) {<br> if l.N &lt;= 0 {<br>  return 0, EOF<br> }<br> if int64(len(p)) &gt; l.N {<br>  p = p[0:l.N]<br> }<br> n, err = l.R.Read(p)<br> l.N -= int64(n)<br> return<br>}</pre><p>The idea is the same, but they only used two variables in the struct. Their variable naming convention is also succinct. It’s just so much Unix-y. Their code is always clever. And when I checked the git blame, i found, obviously that it was mostly Rob’s havoc.</p><p>Just in case, you’re wondering about the trick that’s going on in both of these programs, it’s the fact that we’re reducing the size of the slice where the bytes are read into because the size of the slice limits how much can be read into it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2243bfbe690f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IO in Go / Unix.]]></title>
            <link>https://medium.com/@sumanchapai/io-in-go-unix-a46199b3b110?source=rss-4763fe70368b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a46199b3b110</guid>
            <dc:creator><![CDATA[Suman Chapai]]></dc:creator>
            <pubDate>Sun, 03 Sep 2023 22:21:58 GMT</pubDate>
            <atom:updated>2023-09-03T22:30:57.844Z</atom:updated>
            <content:encoded><![CDATA[<p>Python being my first language, I wasn’t used to the idea that stdin, stdout are merely files (or at least treated as such). Everything is a file idea of Unix still hasn’t sunk well, and this fact, time and again, presents challenges when I am learning something Unix-y. Recently, when learning Go, I faced this challenge again. This article shares that journey.</p><p>The first program that I want to write is a one that reads two numbers as input from user and prints their sum. In Python I would perhaps write something like:</p><pre>a = int(input(&quot;Enter a number: &quot;))<br>b = int(input(&quot;Enter a number: &quot;))<br>print(a + b)</pre><p>And with some error checking, it would perhaps be something like:</p><pre>class IntInputException(Exception):<br>    pass<br><br>def intInput(prompt):<br>    userInput = input(prompt)<br>    # Note floats are invalid<br>    if userInput.isdigit():<br>        return int(userInput)<br>    raise IntInputException(f&quot;Expected integer, got {userInput}&quot;)<br><br>def main():<br>    try:<br>        a = intInput(&quot;Enter a number: &quot;)<br>        b = intInput(&quot;Enter a number: &quot;)<br>    except IntInputException as e:<br>        print(e)<br>        return<br>    print(a + b)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>But Go doesn’t have a builtin input function that reads from standard input. The first way I thought of writing this was something like the following (note it doesn’t have complete implementation)</p><pre>// sum1.go<br>// Ask for two numbers from stdin and print their sum<br>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;io&quot;<br> &quot;os&quot;<br>)<br><br>func main() {<br> prompt := &quot;Enter a number: &quot;<br> a, err := readNumber(prompt)<br> if err != nil {<br>  fmt.Printf(&quot;%s\n&quot;, &quot;Invalid input&quot;)<br>  os.Exit(1)<br> }<br> b, err := readNumber(prompt)<br> if err != nil {<br>  fmt.Printf(&quot;%s\n&quot;, &quot;Invalid input&quot;)<br>  os.Exit(1)<br> }<br> fmt.Println(a + b)<br>}<br><br>func readNumber(prompt string) (int, error) {<br> // Dispaly prompt to stdout<br> fmt.Printf(&quot;%s&quot;, prompt)<br> // Setup a reader to read from stdin<br> var r io.Reader<br> r = os.Stdin<br> sliceToReadInto := make([]byte, 1)<br> r.Read(sliceToReadInto)<br> fmt.Println(&quot;text is&quot;, sliceToReadInto)<br> return 0, nil<br>}</pre><p>I am having some trouble implementing the readNumber function. Precisely, in the line sliceToReadInto := make([]byte, 1) what should be the size of the the slice? Because if it is too small, like in the current case, it looks like the input given for the first line after the first byte is considered to be the input of the second Read call for when the readNumber is called for the second time. If we were to change the size byte to 0, the program doesn’t even wait for user input at all. If we were to make it as big as 100, say, given that the first line isn’t 100 bytes, the input would work, sort of, but only if the first line isn’t more than 100 bytes long. There’s must be something we are missing here.</p><p>Perhaps, we could use a Scanner from the bufio package. What a scanner is supposed to lets us do is Read various tokens. In our case, the input is the standard in and each line of input is a token.</p><pre>// sum2.go<br>package main<br><br>import (<br> &quot;bufio&quot;<br> &quot;fmt&quot;<br> &quot;io&quot;<br> &quot;os&quot;<br>)<br><br>// main function (not shown here) is same as in sum1.go<br><br>func readNumber(prompt string) (int, error) {<br> // Dispaly prompt to stdout<br> fmt.Printf(&quot;%s&quot;, prompt)<br> // Setup a reader to read from stdin<br> var r io.Reader<br> r = os.Stdin<br> // Read the first line of input from stdin<br> // Here what we really want is a scanner that reads the next token, where<br> // the tokens for us are separated by \n<br> s := bufio.NewScanner(r)<br> s.Split(bufio.ScanLines)<br> fmt.Println(&quot;text is&quot;, s.Text())<br> return 0, nil<br>}</pre><p>Here we just created a Scanner and told us that our tokens are new lines by passing the split function bufio.ScanLines).</p><p>However this doesn’t work either. Surprisingly, the program doesn’t even wait for user input. The scanner perhaps sees that there’s nothing to read from the Standard input and just reports empty string as the token each time? I am not sure…</p><p>But why does the first function wait for user input and second doesn’t. Does does it wait and when does it not?</p><p>Definitions of the Read method that Reader has to implmenet as written in the io package might be somewhat helpful in understanding this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-oVdornPwRT9H1yg5875AQ.png" /><figcaption>Read method for a Reader</figcaption></figure><p>Let’s do some experiments changing our readNumber function to print the entire result of the Read.</p><pre>// sum3.go<br>func readNumber(prompt string) (int, error) {<br> // Dispaly prompt to stdout<br> fmt.Printf(&quot;%s&quot;, prompt)<br> // Setup a reader to read from stdin<br> var r io.Reader<br> r = os.Stdin<br> sliceToReadInto := make([]byte, 0)<br> fmt.Println(r.Read(sliceToReadInto))<br> return 0, nil<br>}<br><br>// Results (program didn&#39;t wait for user input)<br>Enter a number: 0 &lt;nil&gt;<br>Enter a number: 0 &lt;nil&gt;<br>0</pre><pre>// sum4.go<br>func readNumber(prompt string) (int, error) {<br> // Dispaly prompt to stdout<br> fmt.Printf(&quot;%s&quot;, prompt)<br> // Setup a reader to read from stdin<br> var r io.Reader<br> r = os.Stdin<br> sliceToReadInto := make([]byte, 1)<br> fmt.Println(r.Read(sliceToReadInto))<br> return 0, nil<br>}<br><br>// Results (program asked for input once, entered 5)<br>Enter a number: 5<br>1 &lt;nil&gt;<br>Enter a number: 1 &lt;nil&gt;<br>0</pre><pre>// sum5.go<br>func readNumber(prompt string) (int, error) {<br> // Dispaly prompt to stdout<br> fmt.Printf(&quot;%s&quot;, prompt)<br> // Setup a reader to read from stdin<br> var r io.Reader<br> r = os.Stdin<br> sliceToReadInto := make([]byte, 100)<br> fmt.Println(r.Read(sliceToReadInto))<br> return 0, nil<br>}<br><br>// Results (program asked for input twice, entered 5, 6)<br>Enter a number: 5<br>2 &lt;nil&gt;<br>Enter a number: 6<br>2 &lt;nil&gt;<br>0</pre><p>In sum3.go and sum4.go the size of our slice to read into is so small that the read can return early. In the case of sum3.go it can return after reading no bytes because the size of our slice is 0, in the case of the sum4.go input is asked for only once because the input entered into the first prompt larger than what is consumed by the first read so the second read consumes the remaining input from after first read.</p><p>In the case of sum5.go though, I am not sure why the program doesn’t wait to read 100 bytes. The read returns after seeing \n perhaps. Not sure why it has to be newline. This part in the definition of read in the io package perhaps permits the read to return early.</p><blockquote>“ If some data is available but not len(p) bytes, Read conventionally returns what is available instead of waiting for more.”</blockquote><p>Well, I think I found the bug that I had in sum2.go because of which the code wasn’t making any prompts to read from the standard in and I think the bug was that I was missing the call to Scan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uA3Q0LPSeG1DO9tF0C98OA.png" /><figcaption>Scan method for Scanner</figcaption></figure><p>We can keep calling Scan, until it returns true. After each Scan completion, we can call Text to get the string of the most recent token, I think.</p><pre>// sum6.go<br>// Ask for two numbers from stdin and print their sum<br>package main<br><br>import (<br> &quot;bufio&quot;<br> &quot;errors&quot;<br> &quot;fmt&quot;<br> &quot;io&quot;<br> &quot;os&quot;<br>)<br><br>var InputErr = errors.New(&quot;Error Reading&quot;)<br><br>func main() {<br> prompt := &quot;Enter a number: &quot;<br> a, err := readNumber(prompt)<br> if err != nil {<br>  fmt.Printf(&quot;%s\n&quot;, &quot;Invalid input&quot;)<br>  os.Exit(1)<br> }<br> b, err := readNumber(prompt)<br> if err != nil {<br>  fmt.Printf(&quot;%s\n&quot;, &quot;Invalid input&quot;)<br>  os.Exit(1)<br> }<br> fmt.Println(a + b)<br>}<br><br>func readNumber(prompt string) (int, error) {<br> // Dispaly prompt to stdout<br> fmt.Printf(&quot;%s&quot;, prompt)<br> // Setup a reader to read from stdin<br> var r io.Reader<br> r = os.Stdin<br> // Read the first line of input from stdin<br> // Here what we really want is a scanner that reads the next token, where<br> // the tokens for us are separated by \n<br> s := bufio.NewScanner(r)<br> s.Split(bufio.ScanLines)<br> if valid := s.Scan(); !valid {<br>  return 0, InputErr<br> }<br> fmt.Println(&quot;text is&quot;, s.Text())<br> return 0, nil<br>}</pre><p>Our solution now kind of works. We have implemented something like a input function in python. It would perhaps be something like:</p><pre>func input(prompt string) (string, error) {<br> fmt.Printf(&quot;%s&quot;, prompt)<br> s := bufio.NewScanner(os.Stdin)<br> if valid := s.Scan(); !valid {<br>  return &quot;&quot;, InputErr<br> }<br> return s.Text(), nil<br>}</pre><p>And now, we’ll implement intInput and show the complete program:</p><pre>// sum7.go<br>// Ask for two numbers from stdin and print their sum<br>package main<br><br>import (<br> &quot;bufio&quot;<br> &quot;errors&quot;<br> &quot;fmt&quot;<br> &quot;os&quot;<br> &quot;strconv&quot;<br>)<br><br>var InputErr = errors.New(&quot;Error Reading&quot;)<br><br>func main() {<br> prompt := &quot;Enter a number: &quot;<br> a, err := intInput(prompt)<br> if err != nil {<br>  fmt.Printf(&quot;%s\n&quot;, &quot;Invalid input&quot;)<br>  os.Exit(1)<br> }<br> b, err := intInput(prompt)<br> if err != nil {<br>  fmt.Printf(&quot;%s\n&quot;, &quot;Invalid input&quot;)<br>  os.Exit(1)<br> }<br> fmt.Println(a + b)<br>}<br><br>func input(prompt string) (string, error) {<br> fmt.Printf(&quot;%s&quot;, prompt)<br> s := bufio.NewScanner(os.Stdin)<br> if valid := s.Scan(); !valid {<br>  return &quot;&quot;, InputErr<br> }<br> return s.Text(), nil<br>}<br><br>func intInput(prompt string) (int64, error) {<br> v, err := input(prompt)<br> if err != nil {<br>  return 0, err<br> }<br> return strconv.ParseInt(v, 10, 64)<br>}</pre><p>But we haven’t fully answered all the questions we had. Perhaps it might be only just if we tried to write the input without the help of Scanner or if we wrote the Scan method for Scanner ourselves.</p><p>Thinking about writing the Scan method, it has to keep reading until it finds the token it’s looking for and set that to some of its data attribute so that the call to Text or Bytes will reveal that token.</p><p>To help us, we have split function to which if we present some bytes, it will give us the next token and the number of bytes to advance the input. If the input we present isn’t sufficiently long as signaled by the split function, we can read more and give it to the split function again.</p><p>Indeed, the kind of problem of choosing the size of the slice that we described in the beginning is indirectly what Scanner has to deal with internally too. Look at these lines in the bufio package:</p><p><a href="https://cs.opensource.google/go/go/+/refs/tags/go1.21.0:src/bufio/scan.go;l=80-82">https://cs.opensource.google/go/go/+/refs/tags/go1.21.0:src/bufio/scan.go;l=80-82</a></p><pre><br>const (<br> // MaxScanTokenSize is the maximum size used to buffer a token<br> // unless the user provides an explicit buffer with Scanner.Buffer.<br> // The actual maximum token size may be smaller as the buffer<br> // may need to include, for instance, a newline.<br> MaxScanTokenSize = 64 * 1024<br><br> startBufSize = 4096 // Size of initial allocation for buffer.<br>)</pre><p>But, of course, they’ll grow the buffer size if needed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a46199b3b110" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>