<?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 Orlando Monteverde on Medium]]></title>
        <description><![CDATA[Stories by Orlando Monteverde on Medium]]></description>
        <link>https://medium.com/@orlmonteverde?source=rss-fe146a4dcdc0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*X_Nrn9NPtCZ_c476mCyM0w.jpeg</url>
            <title>Stories by Orlando Monteverde on Medium</title>
            <link>https://medium.com/@orlmonteverde?source=rss-fe146a4dcdc0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 04:16:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@orlmonteverde/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[Golang and MongoDB with go-mongo-driver — Part 3: Geospatial Queries]]></title>
            <link>https://medium.com/glottery/golang-and-mongodb-with-go-mongo-driver-part-3-geospatial-queries-7decc0cfc92?source=rss-fe146a4dcdc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/7decc0cfc92</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Orlando Monteverde]]></dc:creator>
            <pubDate>Mon, 30 Sep 2019 13:08:51 GMT</pubDate>
            <atom:updated>2019-11-20T15:10:28.329Z</atom:updated>
            <content:encoded><![CDATA[<h3>Golang and MongoDB with go-mongo-driver — Part 3: Geospatial Queries</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ax7-XeL-Gg9GvcdvE_lbEA.png" /><figcaption><a href="https://github.com/mongodb/mongo-go-driver/">MongoDB</a></figcaption></figure><h3>Requirements</h3><ul><li><a href="https://www.mongodb.com/">MongoDB</a> version 3 or higher. Alternatively, a cloud service such as <a href="https://www.mongodb.com/cloud/atlas">Mongodb Atlas</a>.</li><li><a href="https://golang.org/">Go</a> version 1.11 or higher.</li><li><a href="https://github.com/mongodb/mongo-go-driver/">go-mongo-driver</a> version 1.0.3</li></ul><h3>Should I read this post?</h3><p>The short answer is yes. OK, now seriously, this post assumes that you has used <a href="https://golang.org/">Go</a> (Golang) and you have some knowledge of <a href="https://www.mongodb.com/">MongoDB</a>. This is the third part of the post about <a href="https://github.com/mongodb/mongo-go-driver/">go-mongo-driver</a>, an alternative to the well-known <a href="https://labix.org/mgo">mgo</a>. Well, this time we’re going to try the <a href="https://docs.mongodb.com/manual/geospatial-queries/">geospatial queries</a>. If this interests you, well, go ahead!</p><blockquote><strong>NOTE</strong>: If you already know how <em>go-mongo-driver</em> works and just want to learn about <em>geospatial queries</em>, you can go to the <strong>Starting</strong> section.</blockquote><h3>Prepare the workspace</h3><p>For this project, we will use the <a href="https://blog.golang.org/using-go-modules">go modules</a>, if you do not know what I am talking about, you should probably look for it. But you can work on your GOPATH, ignore the “<em>mod commands</em>” and follow the post.</p><p>In the terminal, type the following command, or you can create a directory with a GUI tool, but it is not cool, right?.</p><pre>$ mkdir mongo-golang-geo &amp;&amp; cd $_</pre><p>Inside the new directory, we execute the following command.</p><pre>$ go mod init github.com/&lt;username&gt;/mongo-golang-crud</pre><p>This creates the go.mod file, but do not worry about that now. With that, we have initialized the module and we can download the dependency we need for the project, as below.</p><pre>$ go get -v go.mongodb.org/mongo-driver/mongo@v1.0.3</pre><p>Now, we need to create the file structures. You are free to create these files the way you want, but I use the terminal for this. Just follow me, okay?</p><pre>$ touch main.go point.go location.go mongo.go</pre><p>Well, already the files <strong>location.go</strong>, <strong>main.go</strong>, <strong>mongo.go</strong> and <strong>point.go</strong> in your project folder. These should be as seen below.</p><pre>.<br>├── go.mod<br>├── go.sum<br>├── location.go<br>├── main.go<br>├── mongo.go<br>└── point.go</pre><blockquote><strong>NOTE</strong>: All files belong to the main package, remember to include “<em>package main</em>” in the top part of each * .go file.</blockquote><h3>Starting</h3><p>For a fast advance and considering that we saw the configuration in the <a href="https://medium.com/glottery/golang-and-mongodb-with-go-mongo-driver-part-1-1c43aba25a1">previous publication</a>, we will start with the base code that is shown below.</p><pre>// mongo.go</pre><pre>package main</pre><pre>import (<br>    &quot;context&quot;</pre><pre>    &quot;go.mongodb.org/mongo-driver/mongo&quot;<br>    &quot;go.mongodb.org/mongo-driver/mongo/options&quot;<br>)</pre><pre><em>// DBName Database name.<br></em>const DBName = &quot;geolocation&quot;</pre><pre>var (<br>    conn       *mongo.Client<br>    ctx        = context.Background()<br>    connString string = &quot;mongodb://127.0.0.1:27017/glottery&quot;<br>)</pre><pre><em>// Database collections.<br></em>var (<br>    PointCollection = &quot;points&quot;<br>)</pre><pre><em>// createDBSession Create a new connection with the database.<br></em>func createDBSession() error {<br>    var err error</pre><pre>    conn, err = mongo.Connect(ctx, options.Client().<br>        ApplyURI(connString))<br>    if err != nil {<br>        return err<br>    }</pre><pre>    err = conn.Ping(ctx, nil)<br>    if err != nil {<br>        return err<br>    }</pre><pre>    return nil<br>}</pre><p>Now, try it the connection in main.go.</p><pre>// main.go</pre><pre>package main</pre><pre>import &quot;fmt&quot;</pre><pre>func main() {<br>    if err := createDBSession(); err != nil {<br>        fmt.Println(err)<br>        return<br>    }</pre><pre>    fmt.Println(&quot;Connected&quot;)  // Connected<br>}</pre><h3>The GeoJSON type</h3><blockquote>In MongoDB, you can store geospatial data as <a href="https://docs.mongodb.com/manual/geospatial-queries/#geospatial-geojson">GeoJSON</a> objects or as <a href="https://docs.mongodb.com/manual/geospatial-queries/#geospatial-legacy">legacy coordinate pairs</a>.</blockquote><blockquote>To calculate geometry over an Earth-like sphere, store your location data as <a href="https://docs.mongodb.com/manual/reference/geojson/">GeoJSON objects</a>.</blockquote><blockquote>To specify GeoJSON data, use an embedded document with:</blockquote><blockquote>- a field named type that specifies the <a href="https://docs.mongodb.com/manual/reference/geojson/">GeoJSON object type</a> and</blockquote><blockquote>- a field named coordinates that specifies the object’s coordinates.</blockquote><blockquote>- If specifying latitude and longitude coordinates, list the <strong>longitude</strong> first and then <strong>latitude</strong>:</blockquote><blockquote>Valid longitude values are between -180 and 180, both inclusive.</blockquote><blockquote>Valid latitude values are between -90 and 90, both inclusive.</blockquote><blockquote><a href="https://docs.mongodb.com/manual/geospatial-queries/#geospatial-queries">MongoDB</a></blockquote><p>Go is a statically typed language, so we need to create a type that satisfies the GeoJSON object for geospatial queries in MongoDB.</p><pre>// location.go<br>package main</pre><pre><em>// Location is a GeoJSON type.<br></em>type Location struct {<br>    Type        string    `json:&quot;type&quot; bson:&quot;type&quot;`<br>    Coordinates []float64 `json:&quot;coordinates&quot; bson:&quot;coordinates&quot;`<br>}</pre><pre><em>// </em>NewPoint<em> returns a GeoJSON Point with longitude and latitude.<br></em>func NewPoint(long, lat float64) Location {<br>    return Location{<br>        &quot;Point&quot;,<br>        []float64{long, lat},<br>    }<br>}</pre><p>For this example use the type of point, it is the most used. But it is similar to other types. The New function is a short way to instantiate new points with longitude and latitude.</p><h3>Geospatial Indexes</h3><p>Now we need to create a geospatial index to perform geospatial queries in a collection. Wait, what collection? I forget to create a collection. Let’s do this first.</p><pre>// point.go</pre><pre>package main</pre><pre>import &quot;go.mongodb.org/mongo-driver/bson/primitive&quot;</pre><pre><em>// Point is a simple type with a location for geospatial<br>// queries</em>.<br>type Point struct {<br>    ID       primitive.ObjectID `json:&quot;id&quot; bson:&quot;_id&quot;`<br>    Title    string             `json:&quot;title&quot;`<br>    Location Location           `json:&quot;location&quot;`<br>}</pre><p>Well, it’s time the index.</p><pre>// mongo.go<br>package main</pre><pre>import (<br>    &quot;context&quot;<br>    &quot;time&quot;</pre><pre>    &quot;go.mongodb.org/mongo-driver/mongo&quot;<br>    &quot;go.mongodb.org/mongo-driver/mongo/options&quot;<br>    &quot;go.mongodb.org/mongo-driver/x/bsonx&quot;<br>)</pre><pre><strong>[...]</strong></pre><pre>func createIndex() error {<br>    ctx, cancel := context.<br>        WithTimeout(context.Background(), 10*time.Second)</pre><pre>    defer cancel()<br>    db := conn.Database(DBName)</pre><pre>    indexOpts := options.CreateIndexes().<br>        SetMaxTime(time.Second * 10)</pre><pre><em>    // Index to location 2dsphere type.<br>    </em><strong>pointIndexModel := mongo.IndexModel{<br>        Options: options.Index().SetBackground(true),<br>        Keys:    bsonx.MDoc{&quot;location&quot;: bsonx.String(&quot;2dsphere&quot;)},<br>    }</strong></pre><pre>    pointIndexes := db.Collection(PointCollection).Indexes()<br>    _, err := pointIndexes.CreateOne(<br>        ctx,<br>        pointIndexModel,<br>        indexOpts,<br>    )<br>    if err != nil {<br>        return err<br>    }</pre><pre>    return nil<br>}</pre><p>I don’t stop to explain how the MongoDB Index works, but the <a href="https://medium.com/glottery/golang-and-mongodb-with-go-mongo-driver-part-2-1d0aa64cdbf4">previous publication</a> addressed the topic in more detail. The only novelty is the index itself.</p><blockquote>A 2dsphere index supports queries that calculate geometries on an earth-like sphere. 2dsphere index supports all MongoDB geospatial queries: queries for inclusion, intersection and proximity. For more information on geospatial queries, see <a href="https://docs.mongodb.com/manual/geospatial-queries/">Geospatial Queries</a>.</blockquote><blockquote><a href="https://docs.mongodb.com/manual/core/2dsphere/">MongoDB</a></blockquote><p>We basically do this to make geospatial queries with the geospatial operator. How many times have I said geospatial?</p><h3>Adding points</h3><p>There is no mystery here, inserting a document is the same as we saw in previous publications. But we writing a function called <strong>AddPoint</strong>.</p><pre>// main.go<br>package main</pre><pre>import (<br>    &quot;fmt&quot;</pre><pre>    &quot;go.mongodb.org/mongo-driver/bson/primitive&quot;<br>)</pre><pre>func main() {<br>    if err := createDBSession(); err != nil {<br>        fmt.Println(err)<br>        return<br>    }</pre><pre>    fmt.Println(&quot;Connected&quot;)<br>}</pre><pre><em>// AddPoint adds a new point to the collection.<br></em>func AddPoint(point Point) error {<br>    coll := conn.Database(DBName).Collection(PointCollection)<br>    point.ID = primitive.NewObjectID()</pre><pre>    insertResult, err := coll.InsertOne(ctx, point)<br>    if err != nil {<br>        fmt.Printf(&quot;Could not insert new Point. Id: %s\n&quot;, point.ID)<br>        return err<br>    }</pre><pre>    fmt.Printf(&quot;Inserted new Point. ID: %s\n&quot;, insertResult.InsertedID)</pre><pre>    return nil<br>}</pre><p>Well, now go insert a point.</p><pre>// main.go<br>package main</pre><pre><strong>[...]</strong></pre><pre>func main() {<br>    if err := createDBSession(); err != nil {<br>        fmt.Println(err)<br>        return<br>    }</pre><pre>    if err := createIndex(); err != nil {<br>        fmt.Println(err)<br>        return<br>    }</pre><pre>    fmt.Println(&quot;Connected&quot;)<br>    <strong>p := Point{<br>        Name:     &quot;Central Park&quot;,<br>        Location: NewPoint(-73.97, 40.77),<br>    }</strong></pre><pre>    err := AddPoint(p)<br>    if err != nil {<br>        fmt.Println(err)<br>        return<br>    }<br>}</pre><pre><strong>[...]</strong></pre><h3>Getting points</h3><p>Finally, the most interesting part, Queries!</p><pre><em>// main.go<br>package main</em></pre><pre><strong>[...]</strong></pre><pre><em>// GetPointsByDistance gets all the points that are within the<br>// maximum distance provided in meters.<br></em>func GetPointsByDistance(location Location, distance int) ([]Point, error) {<br>    coll := conn.Database(DBName).Collection(PointCollection)</pre><pre>    var results []Point<br>    <strong>filter := bson.D{<br>        {&quot;location&quot;,<br>            bson.D{<br>                {&quot;$near&quot;, bson.D{<br>                    {&quot;$geometry&quot;, location},<br>                    {&quot;$maxDistance&quot;, distance},<br>            }},<br>        }},<br>    }</strong></pre><pre>    cur, err := coll.Find(ctx, filter)<br>    if err != nil {<br>        return []Point{}, err<br>    }</pre><pre>    for cur.Next(ctx) {<br>        var p Point<br>        err := cur.Decode(&amp;p)<br>        if err != nil {<br>            fmt.Println(&quot;Could not decode Point&quot;)<br>            return []Point{}, err<br>        }<br>        results = append(results, p)<br>    }</pre><pre>    return results, nil<br>}</pre><p>In general, it is not very different from the way of making queries that we have seen before, but we can see some newcomers.</p><blockquote>$near: Returns geospatial objects in proximity to a point. Requires a geospatial index. The <a href="https://docs.mongodb.com/manual/core/2dsphere/">2dsphere</a> and <a href="https://docs.mongodb.com/manual/core/2d/">2d</a> indexes support <a href="https://docs.mongodb.com/manual/reference/operator/query/near/#op._S_near">$near</a>.</blockquote><blockquote>$geometry: Specifies a geometry in <a href="https://docs.mongodb.com/manual/reference/glossary/#term-geojson">GeoJSON</a> format to geospatial query operators.</blockquote><blockquote>$maxDistance: Specifies a maximum distance to limit the results of <a href="https://docs.mongodb.com/manual/reference/operator/query/near/#op._S_near">$near</a> and <a href="https://docs.mongodb.com/manual/reference/operator/query/nearSphere/#op._S_nearSphere">$nearSphere</a> queries. The <a href="https://docs.mongodb.com/manual/core/2dsphere/">2dsphere</a> and <a href="https://docs.mongodb.com/manual/core/2d/">2d</a> indexes support <a href="https://docs.mongodb.com/manual/reference/operator/query/maxDistance/#op._S_maxDistance">$maxDistance</a>.</blockquote><p>But there is still a wide variety of operators, for more information I recommend the <a href="https://docs.mongodb.com/manual/reference/operator/query-geospatial/">official documentation</a>.</p><p>Ok, let’s do the search.</p><pre>// main.go<br>package main</pre><pre><strong>[...]</strong></pre><pre>func main() {</pre><pre><strong>    [...]</strong></pre><pre>    points, err := GetPointsByDistance(NewPoint(-73.97, 40.77), 50)<br>    if err != nil {<br>        fmt.Println(err)<br>        return<br>    }<br>    fmt.Println(points)<br>}</pre><p>Well, this is the basic information about the MongoDB geospatial queries, but we have not touched the surface yet. If you are interested in learning more about the MongoDB queries. I recommend that you review the <a href="https://docs.mongodb.com/manual/tutorial/query-documents/">documentation</a>.</p><p>Soon we will explore more about <a href="https://github.com/mongodb/mongo-go-driver">go-mongo-driver</a> and Go in general. Thanks for reading, see you next time.</p><p><strong>NOTE</strong>: The full code of this publication is available on <a href="https://github.com/orlmonteverde/mongo-golang-geo">GitHub</a>.</p><h3>Acknowledges</h3><p>Thanks to <a href="https://gist.github.com/Lebski">Lebski</a> for sharing this <a href="https://gist.github.com/Lebski/8f9b5992fec0bf175285f1c13b1e5051">github gist</a> about <a href="https://github.com/mongodb/mongo-go-driver/">go-mongo-driver</a>, it was an inspiration for this post</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7decc0cfc92" width="1" height="1" alt=""><hr><p><a href="https://medium.com/glottery/golang-and-mongodb-with-go-mongo-driver-part-3-geospatial-queries-7decc0cfc92">Golang and MongoDB with go-mongo-driver — Part 3: Geospatial Queries</a> was originally published in <a href="https://medium.com/glottery">Glottery</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sending emails with Go (Golang) and Gmail]]></title>
            <link>https://medium.com/glottery/sending-emails-with-go-golang-and-gmail-39bc20423cf0?source=rss-fe146a4dcdc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/39bc20423cf0</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[gmail]]></category>
            <dc:creator><![CDATA[Orlando Monteverde]]></dc:creator>
            <pubDate>Mon, 15 Jul 2019 12:01:01 GMT</pubDate>
            <atom:updated>2020-01-04T16:21:52.245Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j7-0Os9-Sb2yIBMQ08SNWw.png" /><figcaption>Gopher Artwork by <a href="https://github.com/ashleymcnamara/gophers">Ashley McNamara</a></figcaption></figure><h3>Requirements</h3><ul><li>A <a href="https://accounts.google.com/signup/">Gmail account</a>.</li><li><a href="https://golang.org/">Go</a> version 1.10 or higher.</li><li>A few minutes of your time.</li></ul><h3>Should I read this post?</h3><p>Yes, why not? Well, now seriously, this publication assumes that you have used Go (Golang). In this post, we will learn how we can send emails only with the standard Go library and a Gmail account. It’s okay? Go ahead!</p><h3>It’s coding time!</h3><h4>Configuring Gmail</h4><p>To run this program you may need to allow access to less secure applications in Gmail, you can do it from <a href="https://myaccount.google.com/lesssecureapps">this link</a> and activating the switch as shown in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*XHhBHV6LgZ1LbrQuXp9lhg.png" /><figcaption><a href="https://myaccount.google.com/lesssecureapps">Gmail</a></figcaption></figure><h4>Prepare the workspace</h4><p>For this project, we will use the <a href="https://blog.golang.org/using-go-modules">go modules</a>, if you do not know what I am talking about, you should probably look for it. But you can work on your GOPATH, ignore the “<em>mod commands</em>” and follow the post.</p><p>In the terminal, type the following command, or you can create a directory with a GUI tool, but it is not cool, right?.</p><pre>mkdir send-email-gmail &amp;&amp; cd $_</pre><p>Inside the new directory, we execute the following command.</p><pre>go mod init github.com/&lt;username&gt;/send-email-gmail</pre><p>This creates the go.mod file, but do not worry about that now. With that, we have initialized the module and we can start to coding.</p><h4>Importing packages</h4><pre>package main</pre><pre>import (<br>    &quot;fmt&quot;<br>    &quot;net/smtp&quot;<br>)</pre><p>Import all the packages that we need in the publication. If you are using an editor or an IDE with automatic import, you may not need to do it.</p><h4>Set smtp server structure</h4><pre><strong>[...]</strong><br>// smtpServer data to smtp server<br>type smtpServer struct {<br> host string<br> port string<br>}</pre><pre>// Address URI to smtp server<br>func (s *smtpServer) Address() string {<br> return s.host + &quot;:&quot; + s.port<br>}</pre><h4>Sending the email</h4><pre><strong>[...]</strong><br>func main() {</pre><pre><em>    // Sender data.<br>    </em>from := &quot;myuser@gmail.com&quot;<br>    password := &quot;MySecretPassword&quot;</pre><pre><em>    // Receiver email address.<br>    </em>to := []string{<br>        &quot;firstemail@gmail.com&quot;,<br>        &quot;secondemail@gmail.com&quot;,<br>    }</pre><pre><em>    // smtp server configuration.<br>    </em>smtpServer := smtpServer{host: &quot;smtp.gmail.com&quot;, port: &quot;587&quot;}</pre><pre><em>    // Message.<br>    </em>message := []byte(&quot;This is a really unimaginative message, I know.&quot;)</pre><pre><em>    // Authentication.<br>    </em>auth := smtp.PlainAuth(&quot;&quot;, from, password, smtpServer.host)</pre><pre><em>    // Sending email.<br>    </em>err := smtp.SendMail(smtpServer.Address(), auth, from, to, message)</pre><pre>    if err != nil {<br>        fmt.Println(err)<br>        return<br>    }</pre><pre>    fmt.Println(&quot;Email Sent!&quot;)<br>}</pre><p>I think the code is really simple and easy to understand. The sender’s data is <em>hardcoded</em>, this is bad practice, but for our example it works. In practice it is better to use a configuration file, environment variables or similar.</p><p>The message is just a dummy text, but it can be whatever you want. In combination with templates (see package <a href="https://godoc.org/html/template">html/template</a>) it is quite powerful and useful. But it’s a story for another day … and another post.</p><p>The full code of this publication is available on <a href="https://github.com/orlmonteverde/send-email-gmail">GitHub</a>. Thanks for reading, see you next time.</p><p><a href="https://www.buymeacoffee.com/orlmonteverde">Buy Orlando Monteverde a Coffee - BuyMeACoffee.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39bc20423cf0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/glottery/sending-emails-with-go-golang-and-gmail-39bc20423cf0">Sending emails with Go (Golang) and Gmail</a> was originally published in <a href="https://medium.com/glottery">Glottery</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang and MongoDB with go-mongo-driver — Part 2]]></title>
            <link>https://medium.com/glottery/golang-and-mongodb-with-go-mongo-driver-part-2-1d0aa64cdbf4?source=rss-fe146a4dcdc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d0aa64cdbf4</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[Orlando Monteverde]]></dc:creator>
            <pubDate>Mon, 01 Jul 2019 21:45:38 GMT</pubDate>
            <atom:updated>2019-07-10T19:02:16.992Z</atom:updated>
            <content:encoded><![CDATA[<h3>Golang and MongoDB with go-mongo-driver — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XtU2ByqGUYD4O5TQuS2CxQ.png" /><figcaption><a href="https://github.com/mongodb/mongo-go-driver/"><strong>MongoDB</strong></a></figcaption></figure><h3>Requirements</h3><ul><li><a href="https://www.mongodb.com/">MongoDB</a> version 3 or higher. Alternatively, a cloud service such as <a href="https://www.mongodb.com/cloud/atlas">Mongodb Atlas</a>.</li><li><a href="https://golang.org/">Go</a> version 1.10 or higher.</li><li><a href="https://github.com/mongodb/mongo-go-driver/">go-mongo-driver</a> version 1.0.3</li></ul><h3>Should I read this post?</h3><p>The short answer is yes. OK, now seriously, this post assumes that you has used <a href="https://golang.org/">Go</a> (Golang) and you have some knowledge of <a href="https://www.mongodb.com/">MongoDB</a>. This is the second part of the post about <a href="https://github.com/mongodb/mongo-go-driver/">go-mongo-driver</a>, an alternative to the well-known <a href="https://labix.org/mgo">mgo</a>. Well, this time we’re going to test the <a href="https://docs.mongodb.com/manual/indexes/">MongoDB Indexes</a>. If this interests you, well, go ahead!</p><h3>What is a Index?</h3><p>According to <a href="https://docs.mongodb.com/manual/indexes/">MongoDB</a>:</p><blockquote>Indexes are special data structures that store a small portion of the collection’s data set in an easy to traverse form. The index stores the value of a specific field or set of fields, ordered by the value of the field. The ordering of the index entries supports efficient equality matches and range-based query operations. In addition, MongoDB can return sorted results by using the ordering in the index.</blockquote><h3>Prepare the workspace</h3><p>If you followed the <a href="https://medium.com/glottery/golang-and-mongodb-with-go-mongo-driver-part-1-1c43aba25a1">first part</a> of this publication, you should know this; otherwise, simply follow the steps below.</p><p>For this project, we will use the <a href="https://blog.golang.org/using-go-modules">go modules</a>, if you do not know what I am talking about, you should probably look for it. But you can work on your GOPATH, ignore the “<em>mod commands</em>” and follow the post.</p><p>In the terminal, type the following command, or you can create a directory with a GUI tool, but it is not cool, right?.</p><pre>mkdir mongo-golang-indexes &amp;&amp; cd $_</pre><p>Inside the new directory, we execute the following command.</p><pre>go mod init github.com/&lt;username&gt;/mongo-golang-idexes</pre><p>This creates the <strong>go.mod</strong> file, but do not worry about that now. With that, we have initialized the module and we can download the dependency we need for the project, as below.</p><pre>go get -v go.mongodb.org/mongo-driver/mongo@v1.0.3</pre><h3>Starting</h3><p>For a fast advance and considering that we saw the configuration in the <a href="https://medium.com/glottery/golang-and-mongodb-with-go-mongo-driver-part-1-1c43aba25a1">last publication,</a> we will start with the base code that is shown below.</p><pre>package main</pre><pre>import (<br>        &quot;context&quot;<br>        &quot;fmt&quot;<br>        &quot;time&quot;</pre><pre>        &quot;go.mongodb.org/mongo-driver/bson&quot;<br>        &quot;go.mongodb.org/mongo-driver/bson/primitive&quot;<br>        &quot;go.mongodb.org/mongo-driver/mongo&quot;<br>        &quot;go.mongodb.org/mongo-driver/mongo/options&quot;<br>)</pre><pre>const (<br>        DBName          = &quot;glottery&quot;<br>        notesCollection = &quot;notes&quot;<br>        URI = &quot;mongodb://&lt;user&gt;:&lt;password&gt;@&lt;host&gt;/&lt;name&gt;&quot;<br>)</pre><pre>type Note struct {<br>        ID        primitive.ObjectID `bson:&quot;_id&quot; json:&quot;id,omitempty&quot;`<br>        Title     string             `json:&quot;title&quot;`<br>        Body      string             `json:&quot;body&quot;`<br>        CreatedAt time.Time          `bson:&quot;created_at&quot; json:&quot;created_at,omitempty&quot;`<br>        UpdatedAt time.Time          `bson:&quot;updated_at&quot; json:&quot;updated_at,omitempty&quot;`<br>}</pre><pre>func main() {<br>        <em>//</em> <em>Base</em> <em>context.</em><br>        ctx := context.Background()<br>        clientOpts := options.Client().ApplyURI(URI)<br>        client, err := mongo.Connect(ctx, clientOpts)<br>        if err != nil {<br>                fmt.Println(err)<br>                return<br>        }</pre><pre>        db := client.Database(DBName)<br>        coll := db.Collection(notesCollection)<br>}</pre><h3>Adding an index</h3><p>Probably, the most important (and confusing) of the indexes with the go-mongo driver is the need to import the <a href="https://godoc.org/go.mongodb.org/mongo-driver/x/bsonx">bsonx</a> package. Initially, this was confusing to me, in fact, it’s not very intuitive if you ask me. But when you get it, the rest is very easy. Go to code.</p><pre><strong>[...]</strong><br>import (<br>        &quot;context&quot;<br>        &quot;fmt&quot;<br>        &quot;time&quot;</pre><pre>        &quot;go.mongodb.org/mongo-driver/bson/primitive&quot;<br>        &quot;go.mongodb.org/mongo-driver/mongo&quot;<br>        &quot;go.mongodb.org/mongo-driver/mongo/options&quot;</pre><pre>        <strong>&quot;go.mongodb.org/mongo-driver/x/bsonx&quot;</strong><br>)<br><strong>[...]</strong></pre><h4>Index Options</h4><p>We can set several options for the Index such as, for example, the unique restriction, but this is very specific for <a href="https://docs.mongodb.com/manual/indexes/#b-tree">MongoDB</a>. If you want more information, I recommend consulting the <a href="https://docs.mongodb.com/manual/core/index-creation/#index-creation-background">documentation</a>.</p><pre>func main() {<br>       [...]<br>        <br>       <em>//</em> <em>Options</em><br>       <strong>indexOptions := options.Index().SetUnique(true)</strong><br>}</pre><h4>Index Keys</h4><p>Now, let’s define the key (or keys) for the index. Again, this is very specific for MongoDB and I invite you to visit the <a href="https://docs.mongodb.com/manual/indexes/#index-types">Documentation</a>. For this example, we create a <a href="https://docs.mongodb.com/manual/core/index-single/">Single field index</a> for the <em>Title</em> field, the key on this map (Yes, the <strong>bsonx.MDoc</strong> type is a map) represents the field and the value, in this case, can be a positive number (order ascending) or a negative number (descending order).</p><pre><strong>[...]</strong><br>func main() {<br>        <strong>[...]</strong><br>        indexOptions := options.Index().SetUnique(true)<br>        <strong>indexKeys := bsonx.MDoc{<br>                &quot;title&quot;: bsonx.Int32(-1),<br>        }</strong><br>}</pre><h4>The index model</h4><pre><strong>[...]</strong><br>func main() {<br>        <strong>[...]</strong><br>        indexOptions := options.Index().SetUnique(true)<br>        indexKeys := bsonx.MDoc{<br>                &quot;title&quot;: bsonx.Int32(-1),<br>        }</pre><pre>        <strong>noteIndexModel := mongo.IndexModel{<br>                Options: indexOptions,<br>                Keys:    indexKeys,<br>        }</strong><br>}</pre><p>Create index to the collection</p><pre>[...]<br>func main() {<br>        ctx := context.Background()<br>        clientOpts := options.Client().ApplyURI(URI)<br>        client, err := mongo.Connect(ctx, clientOpts)<br>        if err != nil {<br>                fmt.Println(err)<br>                return<br>        }</pre><pre>        db := client.Database(DBName)<br>        coll := db.Collection(notesCollection)<br><br>        indexOptions := options.Index().SetUnique(true)<br>        indexKeys := bsonx.MDoc{<br>                &quot;title&quot;: bsonx.Int32(-1),<br>        }</pre><pre>        noteIndexModel := mongo.IndexModel{<br>                Options: indexOptions,<br>                Keys:    indexKeys,<br>        }</pre><pre>        indexName, err := <strong>coll.Indexes().CreateOne(ctx, noteIndexModel)</strong><br>        if err != nil {<br>                fmt.Println(err)<br>                return<br>        }</pre><pre>        fmt.Println(indexName) // Output: title_-1<br>}</pre><p>Simple, right? Now the title field should be unique and the queries by this field will be more fast.</p><p>I consider important to mention that it is possible to create several Indices at once using the <em>CreateMany</em> method instead of <em>CreateOne</em>, this receives an array of <em>mongo.IndexModel</em>.</p><h3>Text Indexes</h3><blockquote>MongoDB provides <a href="https://docs.mongodb.com/manual/core/index-text/#index-feature-text">text indexes</a> to support text search queries on string content. text indexes can include any field whose value is a string or an array of string elements.</blockquote><p>Another interesting type of index is the text index, very useful for text search. Like the previous one, we make a text index in the following way:</p><pre><strong>[...]</strong><br>func main() {<br>        <strong>[...]</strong><br>        textIndexModel := mongo.IndexModel{<br>                Options: options.Index().SetBackground(true),<br>                Keys: <strong>bsonx.MDoc{<br>                        &quot;title&quot;: bsonx.String(&quot;text&quot;),<br>                        &quot;body&quot;:  bsonx.String(&quot;text&quot;),<br>                },</strong><br>        }</pre><pre>        indexName, err = coll.Indexes().CreateOne(ctx, textIndexModel)<br>        if err != nil {<br>                fmt.Println(err)<br>                return<br>        }</pre><pre>        fmt.Println(indexName)  // Output: title_text_body_text<br>}</pre><h4>Making queries</h4><p>First, we are going to insert some dummy notes to the collection.</p><pre><strong>[...]</strong><br>var notes = []interface{}{<br>        Note{<br>                ID:        primitive.NewObjectID(),<br>                Title:     &quot;First note&quot;,<br>                Body:      &quot;Concurrency is not parallelism&quot;,<br>                CreatedAt: time.Now(),<br>        }, Note{<br>                ID:        primitive.NewObjectID(),<br>                Title:     &quot;Second note&quot;,<br>                Body:      &quot;A little copying is better than a little dependency&quot;,<br>                CreatedAt: time.Now(),<br>        }, Note{<br>                ID:        primitive.NewObjectID(),<br>                Title:     &quot;Third note&quot;,<br>                Body:      &quot;Don&#39;t communicate by sharing memory, share memory by communicating&quot;,<br>                CreatedAt: time.Now(),<br>        }, Note{<br>                ID:        primitive.NewObjectID(),<br>                Title:     &quot;Fourth note&quot;,<br>                Body:      &quot;Don&#39;t just check errors, handle them gracefully&quot;,<br>                CreatedAt: time.Now(),<br>        },<br>}<br><strong>[...]</strong></pre><p>OK, lets to insert dummy notes.</p><pre><strong>[...]</strong><br>func main() {<br>        <strong>[...]</strong><br>        _, err = coll.InsertMany(ctx, notes)<br>        if err != nil {<br>                fmt.Println(err)<br>                return<br>        }<br>}</pre><p>Now, the queries!</p><pre><strong>[...]</strong><br>func main() {<br>        <strong>[...]</strong><br>        n := Note{}<br>        fmt.Println(&quot;First example&quot;)<br>        cursor, err := coll.Find(ctx, bson.M{<br>                &quot;$text&quot;: bson.M{<br>                        &quot;$search&quot;: &quot;note&quot;,<br>                },<br>        })</pre><pre>        for cursor.Next(ctx) {<br>                cursor.Decode(&amp;n)<br>                fmt.Println(n)<br>        }</pre><pre>        fmt.Println(&quot;Second example&quot;)<br>        cursor, err = coll.Find(ctx, bson.M{<br>                &quot;$text&quot;: bson.M{<br>                        &quot;$search&quot;: &quot;gracefully&quot;,<br>                },<br>        })</pre><pre>        for cursor.Next(ctx) {<br>                cursor.Decode(&amp;n)<br>                fmt.Println(n)<br>        }<br>}</pre><p><strong>NOTE:</strong> If we run the binary twice or more, an error is returned. This is due to the attempt to insert again the same notes, which violates the unique constraint that we did before.</p><p>The full code of this publication is available on <a href="https://github.com/orlmonteverde/mongo-golang-indexes/edit/master/README.md">GitHub</a>. Soon we will explore more about <a href="https://github.com/mongodb/mongo-go-driver">go-mongo-driver</a>. Thanks for reading, see you next time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d0aa64cdbf4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/glottery/golang-and-mongodb-with-go-mongo-driver-part-2-1d0aa64cdbf4">Golang and MongoDB with go-mongo-driver — Part 2</a> was originally published in <a href="https://medium.com/glottery">Glottery</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang and MongoDB with go-mongo-driver — Part 1]]></title>
            <link>https://medium.com/glottery/golang-and-mongodb-with-go-mongo-driver-part-1-1c43aba25a1?source=rss-fe146a4dcdc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c43aba25a1</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[Orlando Monteverde]]></dc:creator>
            <pubDate>Mon, 24 Jun 2019 02:04:27 GMT</pubDate>
            <atom:updated>2019-06-24T12:56:07.435Z</atom:updated>
            <content:encoded><![CDATA[<h3>Golang and MongoDB with go-mongo-driver — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XtU2ByqGUYD4O5TQuS2CxQ.png" /><figcaption><a href="https://github.com/mongodb/mongo-go-driver/">MongoDB</a></figcaption></figure><h3>Requirements</h3><ul><li><a href="https://www.mongodb.com/">MongoDB</a> version 3 or higher. Alternatively, a cloud service such as <a href="https://www.mongodb.com/cloud/atlas">Mongodb Atlas</a>.</li><li><a href="https://golang.org/">Go</a> version 1.10 or higher.</li><li><a href="https://github.com/mongodb/mongo-go-driver/">go-mongo-driver</a> version 1.0.3</li></ul><h3>Should I read this post?</h3><p>The short answer is yes. OK, now seriously, this post assumes that you has used Golang and you have some knowledge of MongoDB. The interest of this post is to be an introduction to <a href="https://github.com/mongodb/mongo-go-driver/">go-mongo-driver</a>. This as an alternative to the well-known <a href="https://github.com/globalsign/mgo">mgo</a> package through a simple CRUD. If this interests you, well, go ahead!</p><h3>Prepare the workspace</h3><p>For this project, we will use the <a href="https://blog.golang.org/using-go-modules">go modules</a>, if you do not know what I am talking about, you should probably look for it. But you can work on your GOPATH, ignore the “<em>mod commands</em>” and follow the post.</p><p>In the terminal, type the following command, or you can create a directory with a GUI tool, but it is not cool, right?.</p><pre>mkdir mongo-golang-crud &amp;&amp; cd $_</pre><p>Inside the new directory, we execute the following command.</p><pre>go mod init github.com/&lt;username&gt;/mongo-golang-crud</pre><p>This creates the go.mod file, but do not worry about that now. With that, we have initialized the module and we can download the dependency we need for the project, as below.</p><pre>go get -v go.mongodb.org/mongo-driver/mongo@v1.0.3</pre><h3>Connection with MongoDB</h3><p>First of all we need to make a connection with MongoDB. For this we will use the URI of the database. This is not a <a href="https://docs.mongodb.com/manual/crud/">MongoDB tutorial</a>, so I will not stop to explain details about this database engine.</p><pre>package main</pre><pre>import (<br>    &quot;context&quot;<br>    &quot;fmt&quot;</pre><pre>    &quot;go.mongodb.org/mongo-driver/mongo&quot;<br>    &quot;go.mongodb.org/mongo-driver/mongo/options&quot;<br>)</pre><pre>const (<br>    <em>//</em> <em>Name</em> <em>of</em> <em>the</em> <em>database.</em><br>    DBName = &quot;glottery&quot;<br>    URI = &quot;mongodb://&lt;user&gt;:&lt;password&gt;@&lt;host&gt;/&lt;name&gt;&quot;<br>)</pre><pre>func main() {<br>    <em>//</em> <em>Base</em> <em>context.</em><br>    ctx := context.Background()</pre><pre>    // Options to the database.<br>    clientOpts := options.Client().ApplyURI(URI)<br>    client, err := mongo.Connect(ctx, clientOpts)<br>    if err != nil {<br>        fmt.Println(err)<br>        return<br>    }</pre><pre>    db := client.Database(DBName)<br>    fmt.Println(db.Name()) // output: glottery<br>}</pre><p>Well, the connection is ready. Now we can make interactions with the database.</p><h3>A new collection</h3><p>If you have previously worked with MongoDB, and I hope so because I am leaving many things out, you will know that you use document collections. We are going to use a collection named notes. This collection will store many documents of a simple structure called Note.</p><pre>[...]<br>const (<br>    <em>//</em> <em>Name</em> <em>of</em> <em>the</em> <em>database.</em><br>    DBName = &quot;glottery&quot;<br>    // Name of the collection.<br>    notesCollection = &quot;notes&quot;</pre><pre>    URI = &quot;mongodb://&lt;user&gt;:&lt;password&gt;@&lt;host&gt;/&lt;name&gt;&quot;<br>)<br>[...]</pre><p>Now we define the Note struct. Don’t forget to import the <strong>time</strong> package.</p><pre>type Note struct {<br>    ID primitive.ObjectID `bson:&quot;_id&quot; json:&quot;id,omitempty&quot;`<br>    Title string `json:&quot;title&quot;`<br>    Body string `json:&quot;body&quot;`<br>    CreatedAt time.Time `bson:&quot;created_at&quot; json:&quot;created_at,omitempty&quot;`<br>    UpdatedAt time.Time `bson:&quot;updated_at&quot; json:&quot;updated_at,omitempty&quot;`<br>}</pre><p>Making some small changes in the <strong>main</strong> function.</p><pre>func main() {<br>    [...]<br>    db := client.Database(DBName)<br>    coll := db.Collection(notesCollection)<br>    fmt.Println(coll.Name()) <em>//</em> output: <em>notes</em><br>}</pre><h3>Inserting data</h3><h4>Insert one document</h4><pre>func main() {<br>    [...]<br>    note := Note{}</pre><pre>    <em>//</em> <em>An</em> <em>ID</em> <em>for</em> <em>MongoDB.</em><br>    note.ID = primitive.NewObjectID()<br>    note.Title = &quot;First note&quot;<br>    note.Body = &quot;Some spam text&quot;<br>    note.CreatedAt = time.Now()<br>    note.UpdatedAt = time.Now()<br>    result, err := coll.InsertOne(ctx, note)<br>    if err != nil {<br>        fmt.Println(err)<br>        return<br>    }</pre><pre><em>    //</em> <em>ID</em> <em>of</em> <em>the</em> <em>inserted</em> <em>document.</em><br>    objectID := result.InsertedID.(primitive.ObjectID)<br>    fmt.Println(objectID) // output: ObjectID(&quot;5d100d9c23affb7006dd9cff&quot;)<br>}</pre><h4>Insert many documents</h4><pre>func main() {<br>    [...]</pre><pre>    <em>//</em> <em>Insert</em> <em>Many</em> <em>Documents.</em><br>    notes := []interface{}{}<br>    note2 := Note{}<br>    note2.ID = primitive.NewObjectID()<br>    note2.Title = &quot;First note&quot;<br>    note2.Body = &quot;Some spam text&quot;<br>    note2.CreatedAt = time.Now()<br>    note2.UpdatedAt = time.Now()</pre><pre>    note3 := Note{<br>        ID:        primitive.NewObjectID(),<br>        Title:     &quot;Third note&quot;,<br>        Body:      &quot;Some spam text&quot;,<br>        CreatedAt: time.Now(),<br>        UpdatedAt: time.Now(),<br>    }</pre><pre>    notes = append(notes, note2, note3)<br>    results, err := coll.InsertMany(ctx, notes)<br>    if err != nil {<br>        fmt.Println(err)<br>        return<br>    }</pre><pre>    fmt.Println(results.InsertedIDs)<br>    // output: [ObjectID(&quot;5d100faf685dbd3130446bac&quot;) ObjectID(&quot;5d100faf685dbd3130446bad&quot;)]<br>}</pre><p>As you can see, the <strong>InsertMany</strong> method required a slice of empty interfaces, in addition to the typical context, of course.</p><p>Just like to the <strong>InsertOne</strong> method, this returns the ID, but InsertMany returns a slice of empty interfaces with the objectIDs of the inserted documents.</p><h3>Update one document</h3><p>First, we need to import the bson package, this package comes together with go-mongo-driver. We can import it in this way <em>“</em><strong><em>go.mongodb.org/mongo-driver/bson</em></strong><em>”</em>.</p><pre>func main() {<br>    [...]<br>    <em>//</em> <em>Update</em> <em>a</em> <em>document.</em></pre><pre>    <em>//</em> <em>Parsing</em> <em>a</em> <em>string</em> <em>ID</em> <em>to</em> <em>ObjectID</em> <em>from</em> <em>MongoDB.</em><br>    objID, err := primitive.ObjectIDFromHex(&quot;5d100d9c23affb7006dd9cff&quot;)<br>    if err != nil {<br>        fmt.Println(err)<br>        return<br>    }</pre><pre>    resultUpdate, err := coll.UpdateOne(<br>        ctx,<br>        bson.M{&quot;_id&quot;: objID},<br>        bson.M{<br>            &quot;$set&quot;: bson.M{<br>            &quot;body&quot;:       &quot;Some updated text&quot;,<br>            &quot;updated_at&quot;: time.Now(),<br>            },<br>        },<br>    )</pre><pre>    fmt.Println(resultUpdate.ModifiedCount) // output: 1<br>}</pre><h3>Delete one document</h3><pre>func main() {<br>    [...]<br>    <em>//</em> <em>Delete</em> <em>one</em> <em>document.</em><br>    objID, err = primitive.ObjectIDFromHex(&quot;5d1017bda2dc2ce292e5f16c&quot;)<br>    if err != nil {<br>        fmt.Println(err)<br>        return<br>    }</pre><pre>    resultDelete, err := coll.DeleteOne(ctx, bson.M{&quot;_id&quot;: objID})<br>    if err != nil {<br>        fmt.Println(err)<br>        return<br>    }</pre><pre>    fmt.Println(resultDelete.DeletedCount) // output: 1<br>}</pre><p>Simple, right? Like <strong>DeleteOne</strong> we can use the <strong>DeleteMany</strong> method. Well, to no one’s surprise, <strong>DeleteMany</strong> removes any document that matches the filter.</p><h3>Find Documents</h3><p>Finally, it is time to look for documents in the database, maybe the most typical operation that we should to do.</p><h4>Find one document</h4><pre>func main() {<br>    [...]<br>    <em>//</em> <em>Find</em> <em>documents.</em><br>    objID, err = primitive.ObjectIDFromHex(&quot;5d100d9c23affb7006dd9cff&quot;)<br>    if err != nil {<br>        fmt.Println(err)<br>        return<br>    }</pre><pre>    findResult := coll.FindOne(ctx, bson.M{&quot;_id&quot;: objID})<br>    if err := findResult.Err(); err != nil {<br>        fmt.Println(err)<br>        return<br>    }</pre><pre>    n := Note{}<br>    err = findResult.Decode(&amp;n)<br>    if err != nil {<br>        fmt.Println(err)<br>        return<br>    }</pre><pre>    fmt.Println(n.Body) // output: Some updated text<br>}</pre><h4>Find many documents</h4><pre>func main() {<br>    [...]<br>    notesResult := []Note{}<br>    cursor, err := coll.Find(ctx, bson.M{})<br>    if err != nil {<br>        fmt.Println(err)<br>        return<br>    }</pre><pre>    <em>//</em> <em>Iterate</em> <em>through</em> <em>the</em> <em>returned</em> <em>cursor.</em><br>    for cursor.Next(ctx) {<br>        cursor.Decode(&amp;n)<br>        notesResult = append(notesResult, n)<br>    }</pre><pre>    for _, el := range notesResult {<br>        fmt.Println(el.Title)<br>    }<br>}</pre><p>Well, this is the basic information about the MongoDB queries, but we have not touched the surface yet. If you are interested in learning more about the MongoDB queries. I recommend that you review the <a href="https://docs.mongodb.com/manual/tutorial/query-documents/">documentation</a>. I recommend checking more about the <a href="https://docs.mongodb.com/manual/tutorial/iterate-a-cursor/#read-operations-cursors">cursors</a>.</p><p>Soon we will explore more about <a href="https://github.com/mongodb/mongo-go-driver">go-mongo-driver</a>. Thanks for reading, see you next time.</p><p><strong>NOTE</strong>: The full code of this publication is available on <a href="https://github.com/orlmonteverde/mongo-golang-crud">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c43aba25a1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/glottery/golang-and-mongodb-with-go-mongo-driver-part-1-1c43aba25a1">Golang and MongoDB with go-mongo-driver — Part 1</a> was originally published in <a href="https://medium.com/glottery">Glottery</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API Rest con Go (Golang) y SQLite3]]></title>
            <link>https://medium.com/@orlmonteverde/api-rest-con-go-golang-y-sqlite3-e378af30719c?source=rss-fe146a4dcdc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/e378af30719c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[español]]></category>
            <dc:creator><![CDATA[Orlando Monteverde]]></dc:creator>
            <pubDate>Mon, 18 Mar 2019 17:20:59 GMT</pubDate>
            <atom:updated>2019-04-21T19:36:42.232Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*zjSzr9Nrq25q3f0cSB1xFA.png" /></figure><p>Vamos a comenzar con un proyecto interesante. ¿De qué se trata? Crearemos una <strong>API Rest</strong> con <strong>Go</strong>, solo con la biblioteca estándar (con excepción del driver para el motor de base de datos correspondiente). Para mantenerlo lo más sencillo posible solo tendremos un modelo de datos, una nota, que contará con un título y una descripción.</p><p>Primero debo aclarar que no es estrictamente <strong>Rest</strong>, solo devolveremos respuestas en formato <strong>JSON</strong> porque es el de uso más común y realizaremos un <strong>CRUD</strong> completo.</p><h3>¿Para quién es este tutorial?</h3><p>A efectos prácticos, para cualquiera que desea aprender como realizar una <strong>API Rest</strong> con <strong>Go</strong>, sin embargo se da por hecho que se conocen las bases del lenguaje <strong>Go</strong>, cierto manejo del lenguaje <strong>SQL</strong>, y familiaridad con el modelo Cliente-Servidor.</p><h3>¿Qué necesitamos?</h3><ul><li>Un editor de código, por ejemplo: LiteIDE, Sublime Text, Visual Studio Code, Vim.</li><li>Un navegador web, cómo Google Chrome o Mozilla Firefox.</li><li>Un cliente Rest: Yo prefiero usar cURL, pero Postman es una muy buena opción.</li><li>Compilador de Go, versión 1.5 o superior debería funcionar sin inconvenientes.</li><li>Driver para SQLite3.</li><li>Ganas de aprender.</li></ul><h3>Creando un servidor</h3><p>La biblioteca estándar de <strong>Go</strong> nos proporciona una buena cantidad de herramientas, que reducen la necesidad de utilizar paquetes de terceros (aunque pude extenderse fácilmente de ser necesario). Uno que ocupo con frecuencia y que será el centro de este proyecto es <a href="https://godoc.org/net/http"><em>net/http</em></a>.</p><p>Lo primero que haremos es crear una carpeta para el proyecto, pueden usar el nombre que prefieran, yo lo llamaré <em>go-web-server</em>. Dentro de la carpeta, crearemos un archivo, nuevamente el nombre es lo de menos, yo lo llamaré <strong>main</strong>, lo que si es importante es la extensión, este archivo debe tener extensión .go y su contenido será el siguiente.</p><pre>// main.go<br>package main<br>import (<br>    &quot;fmt&quot;<br>    &quot;log&quot;<br>    &quot;net/http&quot;<br>)</pre><pre><em>// IndexHandler nos permite manejar la petición a la ruta &#39;/&#39;<br>// y retornar &quot;hola mundo&quot; como respuesta al cliente.</em><br><em>func IndexHandler(w http.ResponseWriter, r *http.Request) {</em><br>    <em>fmt.Fprint(w, &quot;hola mundo&quot;)</em><br><em>}</em></pre><pre>func main() {<br>    <em>//</em> <em>Instancia de http.DefaultServerMux</em><br>    mux := http.NewServeMux()</pre><pre>    <em>//</em> <em>Ruta</em> <em>a</em> <em>manejar</em><br>    mux.HandleFunc(&quot;/&quot;, IndexHandler)</pre><pre>    <em>//</em> <em>Servidor</em> <em>escuchando</em> <em>en</em> <em>el</em> <em>puerto</em> <em>8080</em><br>    http.ListenAndServe(&quot;:8080&quot;, mux)<br>}</pre><p>Primero veamos la función manejadora. Si tienen algo de experiencia trabajando del lado del servidor, sabrán que lo más común es recibir peticiones (request) y retornar respuestas (response), de esto se encargan estas funciones, <strong>w</strong> representa la respuesta y <strong>r</strong> la petición, dentro de la función podemos trabajar con estas variables según lo necesitemos.</p><pre>// IndexHandler nos permite manejar la petición a la ruta &#39;/&#39; y<br>// retornar &quot;hola mundo&quot; como respuesta al cliente.<br>func IndexHandler(w http.ResponseWriter, r *http.Request) {<br>    fmt.Fprint(w, &quot;hola mundo&quot;)<br>}</pre><p>En este caso solo respondemos el típico “hola mundo”. Si ejecutan este programa go run main.go, van a su navegador web y se dirigen a <em>localhost:8080</em> podrán ver dicho mensaje. Nada impresionante pero tenemos un servidor funcionando y en muy pocas lineas de código.</p><p>Para escribir la respuesta estamos usando la función <em>Fprint</em> del paquete <a href="https://godoc.org/fmt"><em>fmt</em></a>, este requiere como primer parámetro un tipo de dato que implemente la interfaz <em>io.Writer </em>(básicamente que tenga un método <em>Write</em>), cosa que hace <em>http.ResponseWriter</em>, el segundo parámetro es una cantidad indeterminada de interfaces.</p><p>Lo otro que hicimos fue enviar un código de estado, el <em>StatusOK</em>, habría sido exactamente lo mismo pasar el número <strong>200</strong>, los invito a realizar la prueba, pero el paquete <a href="https://godoc.org/net/http"><em>http</em></a> ya incluye estos códigos como constantes y me parece mas legible así.</p><p>La variable <em>mux</em> es una instancia de <em>http.DefaultServerMux, </em>un puntero a <em>http.ServeMux</em> con las configuraciones por defecto, que utilizaremos para manejar las rutas.</p><h3>Creando el Modelo</h3><p>Como mencioné antes, nuestro único modelo será una nota, sus atributos serán un identificador único, titulo, descripción, fecha de creación y fecha de actualización. Bastante sencillo pero suficiente para realizar un <strong>CRUD</strong> (Crear, Leer, Actualizar y Borrar).</p><p>Para esto crearé otro archivo en el mismo directorio de <strong>main.go</strong> y lo llamaré <strong>note.go</strong>, perfectamente podría mantener todo en el mismo archivo pero de esta manera podemos trabajar más ordenadamente.</p><pre>// note.go<br>package main</pre><pre>import &quot;time&quot;</pre><pre>type Note struct {<br>    ID          int       `json:&quot;id,omitempty&quot;`<br>    Title       string    `json:&quot;title&quot;`<br>    Description string    `json:&quot;description&quot;`<br>    CreatedAt   time.Time `json:&quot;created_at,omitempty&quot;`<br>    UpdatedAt   time.Time `json:&quot;updated_at,omitempty&quot;`<br>}</pre><p>Asumo que ya estas familiarizado con las estructuras de <strong>Go</strong>, así que será una explicación rápida. El campo <em>ID</em> representa un número único para identificar cada registro en la tabla, <em>Title</em> representa el titulo de la nota, <em>Description</em> el cuerpo, <em>CreatedAt</em> la fecha de creación y <em>UpdatedAt</em> la fecha de actualización.</p><p>Quizás se pregunten que son las cadenas de texto que se encuentran junto a los campos de las estructuras, estas son etiquetas que proporcionan información adicional, en este caso para parsear la estructura a <strong>JSON</strong>.</p><p>Por ejemplo `json:&quot;id,omitempty&quot;`, en formato <strong>JSON</strong> el campo <em>ID</em> será identificado como id más apropiado para el formato, y será omitida si el campo se encuentra vació (<em>omitempty</em>), es decir, en su valor cero.</p><h3>Realizando conexión con SQLite3</h3><p>Ahora crearemos un nuevo archivo, lo llamaré connection.go y en este realizaremos la conexión con la base de datos y lo encapsularemos en un función que retorne un puntero a <em>sql.DB</em>, con el que podremos realizar consultas a la base de datos. Muy bien, veamos el código.</p><pre>// connection.go<br>package main</pre><pre>import “database/sql”</pre><pre>// Puntero a la estructura DB, nos permite manejar la<br>// base de datos<br>var db *sql.DB</pre><pre>func GetConnection() *sql.DB {<br>    // Para evitar realizar una nueva conexión en cada llamada a<br>    // la función GetConnection.<br>    if db != nil {<br>        return db<br>    }</pre><pre>    // Declaramos la variable err para poder usar el operador<br>    // de asignación “=” en lugar que el de asignación corta,<br>    // para evitar que cree una nueva variable db en este scope y<br>    // en su lugar que inicialice la variable db que declaramos a<br>    // nivel de paquete.<br>    var err error</pre><pre>    // Conexión a la base de datos<br>    db, err = sql.Open(“sqlite3”, “data.sqlite”)<br>    if err != nil {<br>        panic(err)<br>    }</pre><pre>    return db<br>}</pre><p>Comencemos por el nuevo paquete que importamos <a href="https://godoc.org/database/sql"><em>database/sql</em></a>, que nos permite manejar operaciones con base de datos <strong>SQL</strong>. En este caso la usaremos en conjunto con <strong>SQLite3</strong>, pero es proceso es prácticamente el mismo para otros motores como <strong>MySQL</strong> o <strong>PostgreSQL</strong>.</p><p>La variable <em>db</em> que estamos declarando es un puntero a la estructura <em>DB</em> del paquete <a href="https://godoc.org/database/sql"><em>sql</em></a> y representa un <em>pool</em> de conexiones y nos permite manejar la base de datos (cerrar la conexión, realizar consultas y demás).</p><p>Dentro de la función <em>GetConnection</em> realizamos la conexión a la base de datos, comprobando antes que la variable <em>db</em> que declaramos antes no se encuentre inicializada. En caso de continuar con su valor zero (<em>nil</em>), utilizamos la función <em>Open</em> del paquete <a href="https://godoc.org/database/sql"><em>sql</em></a> para crear una nueva conexiones e inicializar la variable <em>db</em>.</p><p>Hecho esto podemos comenzar a crear los método para nuestro <strong>CRUD</strong>, así que regresaremos al archivo <strong>note.go</strong>.</p><h3>Creando métodos para el CRUD</h3><p>No voy a explicar las consultas <strong>SQL</strong>, como dije antes se requiere cierto nivel de conocimiento en el tema. De igual forma, no realizaremos consultas de mucha complejidad.</p><p>Antes que todo requerimos descargar un driver para poder trabajar con el correspondiente motor de base de datos. En nuestro caso el de <strong>SQLite3</strong> (pueden ver otras opciones <a href="https://golang.org/s/sqldrivers">aquí</a>).</p><p>Como se trate de un paquete de terceros lo descargamos de la siguiente manera: go get -u -v github.com/mattn/go-sqlite3. Los flags son opcionales, <em>-u</em> indica que en caso de ya tener descargado el paquete lo actualice (si es posible) y <em>-v</em> le indica que realice el proceso de manera “verbosa”, es decir que nos de detalles de lo que está haciendo. Personalmente me gusta usar <em>-v</em> porque de otra forma no siento que la descarga esté progresando, no sé, así soy yo.</p><p>Con paquete descargado podemos importarlo en nuestro programa. Pero notarán que el paquete es importado de manera un poco diferente a lo habitual.</p><pre>import (<br>    &quot;errors&quot;<br>    &quot;time&quot;</pre><pre>    // Driver para SQLite3<br>    _ &quot;github.com/mattn/go-sqlite3&quot;<br>)</pre><p>La razón por la que importamos el paquete de esta manera es porque explícitamente no estaremos utilizando ese paquete en el programa y sabemos que <strong>Go</strong> no permite la importación de paquetes que no estemos usando, los invito a realizar la prueba removiendo el “_” e intentando compilar el código.</p><p>Al importarlo con el “_” es posible compilar el código y provocar que se ejecute el método <em>init</em> del paquete, que es lo que necesitamos para trabajar con el motor de base de datos. Veamos ahora el método para crear una nueva nota.</p><pre>func (n Note) Create() error {<br>    // Obtenemos la conexión a la base de datos.<br>    db := GetConnection()</pre><pre>    // Query para insertar los datos en la tabla notes<br>    q := `INSERT INTO notes (title, description, updated_at)<br>            VALUES(?, ?, ?)`</pre><pre>    // Preparamos la petición para insertar los datos de manera<br>    // segura<br>    stmt, err := db.Prepare(q)<br>    if err != nil {<br>        return err<br>    }</pre><pre>    // Nos aseguramos de cerrar el recurso antes de finalizar la<br>    // función gracias a defer.<br>    defer stmt.Close()</pre><pre>    // Ejecutamos la petición pasando los datos correspondientes.<br>    // El orden es importante, corresponde con los “?” del<br>    // string q.<br>    r, err := stmt.Exec(n.Title, n.Description, time.Now())<br>    if err != nil {<br>        return err<br>    }</pre><pre>    // Confirmamos que una fila fuera afectada, debido a que<br>    // insertamos un registro en la tabla. En caso contrario<br>    // devolvemos un error.<br>    if i, err := r.RowsAffected(); err != nil || i != 1 {<br>        return errors.New(“ERROR: Se esperaba una fila afectada”)<br>    }</pre><pre>    // Si llegamos a este punto consideramos que todo el proceso<br>    // fue exitoso y retornamos un nil para confirmar que no<br>    // existe un error.<br>    return nil<br>}</pre><p>Puede verse un poco grande el método <em>Create</em>, debido a los extensos comentarios, pero creo que deja claro el propósito de la función. Obtenemos una conexión a la base de datos, realizamos la petición de inserción y le pasamos los datos correspondientes, si ocurre un error lo retornamos, en caso contrario retornamos un <em>nil</em>, esta es una práctica muy común con <strong>Go</strong>.</p><p>Excelente, ya tenemos un método para crear una nota, ahora vamos como obtener las notas existentes.</p><pre>func (n *Note) GetAll() ([]Note, error) {<br>    db := GetConnection()<br>    q := `SELECT<br>            id, title, description, created_at, updated_at<br>            FROM notes`</pre><pre>    // Ejecutamos la query<br>    rows, err := db.Query(q)<br>    if err != nil {<br>        return []Note{}, err<br>    }</pre><pre>    // Cerramos el recurso<br>    defer rows.Close()</pre><pre>    // Declaramos un slice de notas para que almacene las<br>    // notas que retorna la petición.<br>    notes := []Note{}</pre><pre>    // El método Next retorna un bool, mientras sea true indicará<br>    // que existe un valor siguiente para leer.<br>    for rows.Next() {<br>        // Escaneamos el valor actual de la fila e insertamos el<br>        // retorno en los correspondientes campos de la nota.<br>        rows.Scan(<br>            &amp;n.ID,<br>            &amp;n.Title,<br>            &amp;n.Description,<br>            &amp;n.CreatedAt,<br>            &amp;n.UpdatedAt,<br>        )</pre><pre>        // Añadimos cada nueva nota al slice de notas que<br>        // declaramos antes.<br>        notes = append(notes, *n)<br>    }<br>    return notes, nil<br>}</pre><p>Pueden notar muchas semejanzas con el método <em>Create</em>, así que me concentraré en las diferencias. Notarán que usamos el método <em>Query</em> en lugar del <em>Prepare</em> que usamos antes. En esta ocasión no necesitamos insertar ningún valor a nuestra query, simplemente ejecutarla, así que no hay riesgos como la inyección de <strong>SQL</strong>.</p><p>Usamos un ciclo <em>for</em> para leer cada fila de la respuesta mientras exista una por leer, cosa que confirmamos con el método <em>Next</em> y añadimos cada nota a nuestro slice de notas, que finalmente retornamos junto a un <em>nil</em> para indicar que todo ha funcionado correctamente.</p><p>Para completar este <strong>CRUD</strong> básico requerimos los método <em>Delete</em> y <em>Update</em>, para borrar y actualizar una nota respectivamente. Realmente no hay mucho que explicar al respecto, el proceso es bastante similar a los métodos anteriores.</p><pre>func (n Note) Update() error {<br>    db := GetConnection()<br>    q := `UPDATE notes set title=?, description=?, updated_at=?<br>            WHERE id=?`</pre><pre>    stmt, err := db.Prepare(q)<br>    if err != nil {<br>        return err<br>    }</pre><pre>    defer stmt.Close()</pre><pre>    r, err := stmt.Exec(n.Title, n.Description, time.Now(), n.ID)<br>    if err != nil {<br>        return err<br>    }</pre><pre>    if i, err := r.RowsAffected(); err != nil || i != 1 {<br>        return errors.New(“ERROR: Se esperaba una fila afectada”)<br>    }</pre><pre>    return nil<br>}</pre><p>El método <em>Update</em> es muy parecido al de <em>Create</em>, con la excepción de que en este usamos <strong>WHERE</strong> dentro de la query para limitar la actualización a la nota con el id correspondiente, de otra forma afectaríamos a todas las filas en la tabla y no es lo que buscamos.</p><pre>func (n Note) Delete(id int) error {<br>    db := GetConnection()<br>    q := `DELETE FROM notes<br>            WHERE id=?`</pre><pre>    stmt, err := db.Prepare(q)<br>    if err != nil {<br>        return err<br>    }</pre><pre>    defer stmt.Close()</pre><pre>    r, err := stmt.Exec(id)<br>    if err != nil {<br>        return err<br>    }</pre><pre>    if i, err := r.RowsAffected(); err != nil || i != 1 {<br>        return errors.New(“ERROR: Se esperaba una fila afectada”)<br>    }</pre><pre>    return nil<br>}</pre><p>El método <em>Delete</em> es bastante sencillo, aunque es el único que hasta ahora recibe argumentos, un <em>id</em> de tipo <em>int</em> que usaremos para borrar específicamente la nota con que coincida con dicho <em>id</em>. Ahora volvamos al archivo <strong>main.go</strong> y preparemos las funciones handler.</p><h3>Definiendo las funciones manejadoras</h3><pre>// GetNotesHandler nos permite manejar las peticiones a la ruta<br>// ‘/notes’ con el método GET.<br>func GetNotesHandler(w http.ResponseWriter, r *http.Request) {<br>    // Puntero a una estructura de tipo Note.<br>    n := new(Note)</pre><pre>    // Solicitando todas las notas en la base de datos.<br>    notes, err := n.GetAll()<br>    if err != nil {<br>        http.Error(w, err.Error(), http.StatusNotFound)<br>        return<br>    }</pre><pre>    // Convirtiendo el slice de notas a formato JSON,<br>    // retorna un []byte y un error.<br>    j, err := json.Marshal(notes)<br>    if err != nil {<br>        http.Error(w, err.Error(), http.StatusBadRequest)<br>        return<br>    }</pre><pre>    // Escribiendo el código de respuesta.<br>    w.WriteHeader(http.StatusOK)</pre><pre>    // Estableciendo el tipo de contenido del cuerpo de la<br>    // respuesta.<br>    w.Header().Set(“Content-Type”, “application/json”)</pre><pre>    // Escribiendo la respuesta, es decir nuestro slice de notas<br>    // en formato JSON.<br>    w.Write(j)<br>}</pre><p>El primer handler es <em>GetNotesHandler</em>, que obtiene y retorna todas las notas en la base de datos. Haciendo uso del método <em>GetAll</em> que definimos para el tipo <em>Note</em>, podemos obtener todas las notas y con la función <em>Marshal</em> del paquete <a href="https://godoc.org/encoding/json"><em>json</em></a> (no olviden importarlo:<em> “encoding/json”</em>) generamos el <strong>JSON</strong> equivalente que finalmente escribimos en la respuesta.</p><pre>// CreateNotesHandler nos permite manejar las peticiones a la ruta<br>// ‘/notes’ con el método POST.<br>func CreateNotesHandler(w http.ResponseWriter, r *http.Request) {<br>    var note Note</pre><pre>// Tomando el cuerpo de la petición, en formato JSON, y<br>    // decodificándola e la variable note que acabamos de<br>    // declarar.<br>    err := json.NewDecoder(r.Body).Decode(&amp;note)<br>    if err != nil {<br>        http.Error(w, err.Error(), http.StatusBadRequest)<br>        return<br>    }</pre><pre>// Creamos la nueva nota gracias al método Create.<br>    err = note.Create()<br>    if err != nil {<br>        http.Error(w, err.Error(), http.StatusInternalServerError)<br>        return<br>    }</pre><pre>    w.WriteHeader(http.StatusOK)<br>}</pre><p>La función <em>CreateNotesHandler</em> es bastante parecida a la anterior pero, en lugar de convertir un tipo de <strong>Go</strong> a <strong>JSON</strong>, tomamos el <strong>JSON</strong> enviado en el cuerpo de la petición y lo decodificamos en una variable de tipo <em>Note</em>.</p><pre>// UpdateNotesHandler nos permite manejar las peticiones a la ruta<br>// ‘/notes’ con el método UPDATE.<br>func UpdateNotesHandler(w http.ResponseWriter, r *http.Request) {<br>    var note Note</pre><pre>err := json.NewDecoder(r.Body).Decode(&amp;note)<br>    if err != nil {<br>        http.Error(w, err.Error(), http.StatusBadRequest)<br>        return<br>    }</pre><pre>    // Actualizamos la nota correspondiente.<br>    err = note.Update()<br>    if err != nil {<br>        http.Error(w, err.Error(), http.StatusInternalServerError)<br>        return<br>    }</pre><pre>    w.WriteHeader(http.StatusOK)<br>}</pre><p>En lo que respecta a la función <em>UpdateNotesHandler</em>, es básicamente igual a la función <em>CreateNotesHandler</em> reemplazando el método <em>Create</em> por <em>Update</em>, por lo que no creo que haga falta ninguna explicación adicional.</p><pre>// DeleteNotesHandler nos permite manejar las peticiones a la ruta<br>// ‘/notes’ con el método DELETE.<br>func DeleteNotesHandler(w http.ResponseWriter, r *http.Request) {<br>    // obtenemos el valor pasado en la url como query<br>    // correspondiente a id, del tipo /notes?id=3.<br>    idStr := r.URL.Query().Get(&quot;id&quot;)</pre><pre>    // Verificamos que no esté vacío.<br>    if idStr == &quot;&quot; {<br>         http.Error(w, &quot;Query id es requerido&quot;,<br>             http.StatusBadRequest)<br>         return<br>    }</pre><pre>    // Convertimos el valor obtenido del query a un int, de ser<br>    // posible.<br>    id, err := strconv.Atoi(idStr)<br>    if err != nil {<br>         http.Error(w, “Query id debe ser un número”,<br>             http.StatusBadRequest)<br>         return<br>    }</pre><pre>    var note Note</pre><pre>    // Borramos la nota con el id correspondiente.<br>    err = note.Delete(id)<br>    if err != nil {<br>        http.Error(w, err.Error(), http.StatusInternalServerError)<br>        return<br>    }</pre><pre>    w.WriteHeader(http.StatusOK)<br>}</pre><p>Finalmente tenemos la función encargada del método para borrar, <em>DeleteNotesHandler</em>, esta es muy parecida a las anteriores, con la particularidad de obtener el valor de <em>id</em> pasado mediante un query en su url (<em>r.URL.Query().Get(“id”)</em>) que originalmente es de tipo <em>string</em> por lo que convertimos el <em>id</em> a tipo <em>int</em> gracias a la función <em>Atoi</em> del paquete <a href="https://godoc.org/strconv"><em>strconv</em></a> (no olviden importarlo:<em> “strconv”</em>).</p><p>Existen otras formas de pasar este valor, una muy común es pasarlo como un parámetro en la <strong>url</strong>, esa manera me parece visualmente mas agradable, pero realizar el código desde cero habría complicado un poco el ejemplo y la intención es mantenerlo lo mas sencillo posible, otra opción muy común es usar algún paquete de terceros (véase <a href="https://github.com/go-chi/chi/">go-chi/chi</a> o <a href="https://github.com/gorilla/mux">gorilla/mux</a>) para facilitarnos el trabajo.</p><p>Ya con nuestro <em>id</em>, podemos llamar al método <em>Delete</em> y borrar la nota correspondiente. Excelente, ya tenemos una función manejadora para cada caso ¿Y ahora que hacemos con ellas? Necesitamos pasarlas a nuestro <em>mux</em> con el método <em>HandleFunc</em>, el detalle es que solo podemos vincular uno a cada ruta particular y lo que buscamos es que todos respondan a la ruta <em>/notes</em> pero se llame a una función u otra según el método de de la petición. He aquí una solución.</p><pre>// NotesHandler nos permite manejar la petición a la ruta ‘/notes’ // y pasa el control a la función correspondiente según el método<br>// de la petición.<br>func NotesHandler(w http.ResponseWriter, r *http.Request) {<br>    switch r.Method {<br>        case http.MethodGet:<br>            GetNotesHandler(w, r)<br>        case http.MethodPost:<br>            CreateNotesHandler(w, r)<br>        case http.MethodPut:<br>            UpdateNotesHandler(w, r)<br>        case http.MethodDelete:<br>            DeleteNotesHandler(w, r)<br>        default:<br>            // Caso por defecto en caso de que se realice una<br>            // petición con un método diferente a los esperados.<br>            http.Error(w, &quot;Metodo no permitido&quot;,<br>                http.StatusBadRequest)<br>            return<br>    }<br>}</pre><p>Esta función llamada <em>NotesHandler</em> se encargará de recibir todas las peticiones a la ruta <em>/notes</em> y, según el método de la petición, pasar el control a la función correspondiente, además de definir una acción por defecto en caso de recibir una petición con un método diferente a los esperados. No hay que olvidar añadir la nueva <em>HandleFunc</em> a nuestro <em>mux</em> de la siguiente manera: <em>mux.HandleFunc(“/notes”, NotesHandler)</em>.</p><p>Hasta aquí ya tenemos nuestra <strong>API</strong> completa, felicitaciones. Aunque hay un detalle más que me gustaría cubrir, si en este momento compilamos y ejecutamos nuestra aplicación todo debería funcionar sin problemas, pero al realizar peticiones a la ruta <em>/notes</em> obtendremos un error, debido a que aún no existe la tabla <em>notes</em> en la base de datos. Es perfectamente lógico debido a que nunca la creamos.</p><h3><strong>Migraciones</strong></h3><p>Es posible crear la tabla manualmente, usar algún cliente externo, incluso una herramienta gráfica. Pero me parece más adecuado darle a nuestra aplicación la opción de crear inicialmente las tablas en la base de datos. Para esto crearemos una nueva función en el archivo<strong> connection.go</strong>.</p><pre>func MakeMigrations() error {<br>    db := GetConnection()</pre><pre>    q := `CREATE TABLE IF NOT EXISTS notes (<br>            id INTEGER PRIMARY KEY AUTOINCREMENT,<br>            title VARCHAR(64) NULL,<br>            description VARCHAR(200) NULL,<br>            created_at TIMESTAMP DEFAULT DATETIME,<br>            updated_at TIMESTAMP NOT NULL<br>         );`</pre><pre>    _, err := db.Exec(q)<br>    if err != nil {<br>        return err<br>    }</pre><pre>    return nil<br>}</pre><p>Con la función <em>MakeMigrations</em> podemos crear, si aún no existen, las tablas o tabla en este caso, antes de comenzar a realizar peticiones. Interesante ¿Dónde la llamamos? Lo haremos en <strong>main.go</strong>, además de darle a nuestro programa la opción de pasar un <strong>flag</strong> al momento de ejecutarlo que indicará si debe o no realizar las migraciones.</p><pre>func main() {<br>...</pre><pre>    // flag para realizar la creación de las tablas en la base<br>    // de datos.</pre><pre>    migrate := flag.Bool(<br>        &quot;migrate&quot;, false, &quot;Crea las tablas en la base de datos&quot;,<br>    )</pre><pre>    // Parseando todas las flags<br>    flag.Parse()<br>    if *migrate {<br>        if err := MakeMigrations(); err != nil {<br>        log.Fatal(err)<br>    }<br>}</pre><pre>...<br>}</pre><p>La magia de esto es cortesía del paquete <a href="https://godoc.org/flag"><em>flag</em></a> (otra vez, no olviden importarlo:<em> “flag”</em>), este paquete nos facilita el trabajo con los flags, en esta ocasión usaremos uno de tipo <em>bool</em>, pero existen más opciones, los invito a explorar el paquete. Un detalle importante es el llamado a la función <em>Parse</em> de este paquete, que parsea todos los flags, debe ser llamado después declaración de todos los flags pero antes de que se acceda al valor de estas.</p><p>Ahora sí, tenemos una <strong>API</strong> completa y funcional desarrollada casi en la totalidad con la biblioteca estándar de Go, en el futuro mostraré ejemplos utilizando paquetes de terceros para facilitarnos el trabajo, abordaremos otros puntos relevantes como los <strong>middlewares</strong>.</p><h3>Realizando peticiones</h3><p>En primer lugar realicemos la compilación: go build. Una vez compilado lo ejecutamos con el flag <em>-migrate</em> para que la tabla <em>notes</em> sea creada: ./go-web-server -migrate. Con esto deberiamos ver en la terminal el mensaje “<em>Corriendo en </em><a href="http://localhost:8080/"><em>http://localhost:8080</em></a>”.</p><p>Para realizar peticiones a nuestra API utilizaré <a href="https://curl.haxx.se/">cURL</a>, siéntanse libres de usar el cliente <strong>Rest</strong> de su preferencia. Mientras el servidor está corriendo, desde otra terminal procedemos a realizar las peticiones.</p><h4>Creando una nota</h4><pre>curl -X POST <a href="http://localhost:8080/notes">http://localhost:8080/notes</a> -H &#39;Content-Type: application/json&#39; -d &#39;{&quot;title&quot;: &quot;Primera nota&quot;, &quot;description&quot;: &quot;Esta es una nota de prueba&quot;}&#39;</pre><h4>Obteniendo notas</h4><pre>curl -X GET <a href="http://localhost:8080/notes">http://localhost:8080/notes</a></pre><h4>Editando una nota</h4><pre>curl -X PUT <a href="http://localhost:8080/notes">http://localhost:8080/notes</a> -H &#39;Content-Type: application/json&#39; -d &#39;{&quot;id&quot;: 1, &quot;title&quot;: &quot;Primera nota editada&quot;, &quot;description&quot;: &quot;Esta es una nota de prueba editada&quot;}&#39;</pre><h4>Borrando una nota</h4><pre>curl -X DELETE <a href="http://localhost:8080/notes">http://localhost:8080/notes</a>?id=1</pre><h3>Conclusiones</h3><p><strong>Go</strong> es un lenguaje excelente para desarrollar <strong>API</strong>, con muy buen performance y una biblioteca estándar muy completa. No existe obligación de utilizar algún framework para desarrollar aplicaciones web, aunque hay muchos para elegir. Fácilmente podemos extender las funcionalidades que nos ofrece la biblioteca estándar con paquetes propios o de terceros según sea necesario.</p><p>Continuaré compartiendo contenido sobre este simpático lenguaje principalmente enfocado a desarrollo web. Las dudas y sugerencias son totalmente bienvenidas, espero que les sea de utilidad. Hasta la próxima.</p><p><strong>NOTA:</strong> El código antes explicado se encuentra completo y disponible es <a href="https://github.com/orlmonteverde/go-api-with-sqlite">este repositorio</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e378af30719c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Estructuras de control de flujo ne Go (Golang)]]></title>
            <link>https://medium.com/@orlmonteverde/estructuras-de-control-de-flujo-ne-go-golang-4af194aee556?source=rss-fe146a4dcdc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/4af194aee556</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[spanish]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Orlando Monteverde]]></dc:creator>
            <pubDate>Wed, 28 Nov 2018 14:01:01 GMT</pubDate>
            <atom:updated>2018-12-12T17:44:55.655Z</atom:updated>
            <content:encoded><![CDATA[<h3>Estructuras de control de flujo en Go (Golang)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*4D25W5vN37XoNzsexJeHFQ.png" /></figure><p>Para aprovechar al máximo este artículo es recomendable tener al menos conociemiento básico del lenguaje, si los tienes o aceptas el desafío, entonces momencemos.</p><h3>Estructuras condicionales</h3><h4>If básico</h4><pre>package main</pre><pre>import &quot;fmt&quot;</pre><pre>func main() {<br>   encendido := true</pre><pre>   if encendido {<br>      fmt.Println(&quot;Está encendido&quot;)<br>   }<br>}</pre><p>Notarán que es muy parecido a la sintaxis de C o a la mayoría de los lenguajes inspirados en este, la principal diferencia es que los paréntesis alrededor de la condición no son obligatorios, pero de igual forma comprueba si dicha condición es verdadera y en caso de que así sea, realiza las instrucciones que se encuentran dentro de sus respectivas llaves, en caso contrario las instrucciones son ignoradas, nada raro hasta el momento. Bastante útil, pero ¿Que sucede si necesito que se ejecute una instrucción en caso de que a condición resulte falsa?</p><h4>If-else</h4><pre>package main</pre><pre>import &quot;fmt&quot;</pre><pre>func main() {<br>    encendido := false</pre><pre>    if encendido {<br>        fmt.Println(&quot;Está encendido&quot;)<br>    } else {<br>        fmt.Println(&quot;Está apagado&quot;)<br>    }<br>}</pre><p>Perfecto, la confiable instrucción else al rescate. En este caso la condición sea evaluada como falsa, las instrucciones dentro del if son ignoradas y se ejecutan las del else.</p><p>Otra caso frecuente es necesitar comprobar más de una condición, fácilmente podrías anidar condicionales (colocar otro if dentro del bloque del else, por ejemplo), pero dependiendo del caso podría ser mas adecuado simplemente usar la estructura <em>else-if</em>, aunque será necesario recurrir a un ejemplo diferente al anterior.</p><h4>Else-If</h4><pre>package main</pre><pre>import &quot;fmt&quot;</pre><pre>func main() {<br>   var edad uint8 = 180</pre><pre>   if edad &gt; 150 {<br>       fmt.Println(&quot;¿Eres inmortal?&quot;)<br>   } else if edad &gt;= 18 {<br>       fmt.Println(&quot;Eres mayor de edad&quot;)<br>   } else {<br>       fmt.Println(&quot;Eres menor de edad&quot;)<br>   }<br>}</pre><p>Hasta el momento nada fuera de lo común, me parece, ahora veamos algo más propio de <strong>Go</strong>.</p><h4>If con declaración corta</h4><pre>package main</pre><pre>import &quot;fmt&quot;</pre><pre>func main() {<br>   if edad := -5; edad &gt; 150 {<br>       fmt.Println(&quot;¿Eres inmortal?&quot;)<br>   } else if edad &gt;= 18 {<br>       fmt.Println(&quot;Eres mayor de edad&quot;)<br>   } else if edad &lt; 18 &amp;&amp; edad &gt; 0 {<br>       fmt.Println(&quot;Eres menor de edad&quot;)<br>   } else {<br>       fmt.Println(&quot;Edad fuera del rango&quot;)<br>   }<br>}</pre><p>Así es, if permite ejecutar una declaración corta antes de comenzar a evaluar las condiciones, es importante resaltar que el ámbito de esa variable está limitado a la propia estructura condicional, intentar acceder a ella desde fuera generará un error al momento de compilar.</p><h4>Switch básico</h4><p>Como alternativa a múltiples <em>else-if</em> contamos con switch.</p><pre>package main</pre><pre>import &quot;fmt&quot;</pre><pre>func main() {<br>    switch dias := 1; dias {<br>    case 0:<br>        fmt.Println(&quot;Lunes&quot;)<br>    case 1:<br>        fmt.Println(&quot;Martes&quot;)<br>    case 2:<br>        fmt.Println(&quot;Miercoles&quot;)<br>    case 3:<br>        fmt.Println(&quot;Jueves&quot;)<br>    case 4:<br>        fmt.Println(&quot;Viernes&quot;)<br>    case 5:<br>        fmt.Println(&quot;Sabado&quot;)<br>    case 6:<br>        fmt.Println(&quot;Domingo&quot;)<br>    default:<br>        fmt.Println(&quot;Desconocido&quot;)<br>    }<br>}</pre><h4>Switch sin condición</h4><pre>package main</pre><pre>import &quot;fmt&quot;</pre><pre>func main() {<br>    var edad uint8 = 18</pre><pre>    switch {<br>    case edad &gt;= 150:<br>        fmt.Println(&quot;¿Eres inmortal?&quot;)<br>    case edad &gt;= 18:<br>        fmt.Println(&quot;Eres mayor de edad&quot;)<br>    default:<br>        fmt.Println(&quot;Eres menor de edad&quot;)<br>    }<br>}</pre><p>Dependiendo de la ocasión es una opción elegante y eficiente, pero en este momento me gustaría resaltar algo, si aún no lo notan, no es necesario utilizar <em>break</em> al final de cada caso para evitar que continúe ejecutando los posteriores, genial, pero si necesitas que lo haga, basta con colocar la palabra reservada fallthrough al final del caso para que continúe con el siguiente.</p><h3>Ciclos en Go</h3><p>Suficiente de condicionales, veamos los ciclos, probablemente se lleven una sorpresa, pero el único constructor para ciclos en <strong>Go</strong> es for, no se preocupen, es el único que van a necesitar, lo prometo.</p><h4>Ciclo for común</h4><pre>package main</pre><pre>import &quot;fmt&quot;</pre><pre>func main() {<br>    for i := 0; i &lt; 10; i++ {<br>        fmt.Println(i)<br>    }<br>}</pre><p>No hay mucho que decir, el ciclo for de toda la vida para aquellos que conozcan lenguajes como C, Java, JavaScript, entre otros. Lo único <em>novedoso</em> sería el hecho de que, al igual que con los condicionales, no son necesarios los paréntesis.</p><h4>For estilo while</h4><pre>package main</pre><pre>import &quot;fmt&quot;</pre><pre>func main() {<br>    var i = 0</pre><pre>    for i &lt; 10 {<br>        fmt.Println(i)<br>        i++<br>    }<br>}</pre><p>Como mencioné anteriormente, for es el único constructor de ciclos en <strong>Go</strong>, pero es bastante flexible.</p><h4>For-range</h4><pre>package main</pre><pre>import &quot;fmt&quot;</pre><pre>func main() {<br>    for indice, letra := range &quot;hola mundo&quot; {<br>        fmt.Println(indice, string(letra))<br>    }<br>}</pre><p>Con esta variación del ciclo for es posible recorrer facilmente colecciones como arreglos, mapas, entre otros.</p><h4>For-forever</h4><pre>package main</pre><pre>import &quot;fmt&quot;</pre><pre>func main() {<br>    for {<br>        fmt.Println(&quot;Hola&quot;)<br>    }<br>}</pre><p>Y así es como podemos hacer un ciclo infinito intencional. Personalmente me resulta de lo más práctico, y esos pequeños detalles enamoran.</p><h3>Defer</h3><p>Ahora uno no tan común. <strong>Defer</strong> permite realizar una declaración que se ejecutará al final de la función, antes del retorno, sin importar en que nivel de la misma fue declarada. Veamos un ejemplo.</p><pre>package main</pre><pre>import &quot;fmt&quot;</pre><pre>func main() {<br>    // Se imprime al final<br>    defer fmt.Println(&quot;primera&quot;)</pre><pre>    // Se imprime después de &quot;Hola mundo&quot;<br>    defer fmt.Println(&quot;segunda&quot;)</pre><pre>    fmt.Println(&quot;Hola mundo&quot;)<br>}</pre><p>Si se están preguntando que utilidad tiene, es perfecta para cerrar recursos, como archivos y conexiones a bases de datos, en <strong>Go</strong> se acostumbra usar justo debajo de la declaración donde se abre el recurso para no olvidar cerrarlo, sabes que de todas formas se ejecutará al final. Otra cosa a tener en cuenta respecto a defer es que si hay mas de uno en la función se ejecutarán en el orden inverso en el que fueron declarados.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4af194aee556" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Conociendo Go (Golang)]]></title>
            <link>https://medium.com/@orlmonteverde/conociendo-go-golang-2f6b3cbc96ee?source=rss-fe146a4dcdc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f6b3cbc96ee</guid>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[español]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Orlando Monteverde]]></dc:creator>
            <pubDate>Mon, 26 Nov 2018 14:01:01 GMT</pubDate>
            <atom:updated>2018-12-12T23:17:57.305Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*4D25W5vN37XoNzsexJeHFQ.png" /></figure><p>En esta ocasión haré un pequeña introducción a este interesante lenguaje de programación, comencemos con una cita a la siempre útil <a href="https://es.wikipedia.org/wiki/Go_(lenguaje_de_programaci%C3%B3n)">wikipedia</a><a href="https://es.wikipedia.org/wiki/Go_(lenguaje_de_programaci%C3%B3n)).">.</a></p><blockquote>Go es un lenguaje de programación concurrente y compilado inspirado en la sintaxis de C. Ha sido desarrollado por Google, y sus diseñadores iniciales son Robert Griesemer, Rob Pike y Ken Thompson. Actualmente está disponible en formato binario para los sistemas operativos Windows, GNU/Linux, FreeBSD y Mac OS X, pudiendo también ser instalado en estos y en otros sistemas con el código fuente. — Wikipedia</blockquote><h3>Características principales</h3><p>- Está inspirado en el lenguaje C<br>- Es concurrente<br>- Soporta la orientación a objetos aunque de una manera bastante particular<br>- Es de tipado estático<br>- Es compilado<br>- Es OpenSource<br>- Desarrollado por Google<br>- Posee recolector de basura</p><p>Como pudieron leer, este lenguaje se inspira en C, por lo que los programadores que estén familiarizados con dicho lenguaje se sentirán a gusto en <strong>Go</strong>, admito que no es mi caso pero aún así es fácil comenzar con él.</p><p>Aunque C no es un lenguaje orientado a objetos, <strong>Go</strong> si soporta este paradigma, pero lo hace de una manera diferente a otros lenguajes populares, como Java o C#.</p><p>A pesar de ser un lenguaje compilado y de tipado estático posee características que lo hacen parecer interpretado y de tipado dinámico, posiblemente sea debido a mi <em>background</em> pero me recuerda mucho a Python.</p><h3>La hora del código</h3><h4>Estructura básica de un programa</h4><pre>package main  // Nombre del paquete</pre><pre>import &quot;fmt&quot;  // Importando paquete</pre><pre>// Función principal del programa<br>func main() {<br>    fmt.Println(&quot;Go es genial&quot;)  // Imprimiendo por consola<br>}</pre><p>Como pueden ver, todo programa en <strong>Go</strong> debe pertenecer a un paquete, el paquete main es especial, la ejecución de los programas inicia en este paquete.</p><p>Por convención el nombre del paquete debe coincidir con el nombre de la carpeta que lo contiene, puedes crear todos los paquetes que necesites y llamarlos según lo requieras como ocurre con los módulos/paquetes en otros lenguajes, para este fin se emplea la palabra reservada import seguida del nombre del paquete. Por otro lado, la función main también es especial, siendo el punto inicial de ejecución de un programa en Go.</p><h4>Variables</h4><pre>package main</pre><pre>import &quot;fmt&quot;</pre><pre>func main() {<br>    var estatura float32  // Número real<br>    var edad int              // Número entero<br>    var activo bool         // Booleano<br>    var nombre string     // Cadena de texto</pre><pre>fmt.Println(&quot;Variables&quot;)<br>    fmt.Println(&quot;estatura:&quot;, estatura)<br>    fmt.Println(&quot;edad:&quot;, edad)<br>    fmt.Println(&quot;activo&quot;, activo)<br>    fmt.Println(&quot;nombre&quot;, nombre)<br>}</pre><p>Go tiene una amplia variedad de tipos de variables, aquí sólo les muestro las básicas, si desean profundizar en el tema los invito a revisar la <a href="https://golang.org/ref/spec#Types">documentación</a>, conocer los tipos de variables es fundamental para optimizar los programas, nos permite reservar el espacio en memoria adecuado según la necesidad.</p><p>Ahora, si observan detenidamente el fragmento de código anterior, notaran que las variables se declaran con la palabra reservada var, seguidas del identificador de dicha variable y el tipo de dato, pero no es la única forma de declarar una variable, en breve les mostraré otras opciones.</p><p>Otra cosa que quizás notaron es que las estoy mandando a imprimir, pero nunca les dí un valor, es probable que piensen que esto generaría un error, o retornaría algún valor indefinido, pero este no es el caso, <strong>Go</strong> tiene valores iniciales para cada tipo de variables, por ejemplo: una cadena vacía para las string, 0 para los números y false para los booleanos, es importante tener eso en cuenta.</p><pre>package main</pre><pre>import &quot;fmt&quot;</pre><pre>func main() {<br>    var estatura float32 = 1.78 // Asignando valor al declarar<br>    var edad = 26               // Infiriendo tipo de dato de la asignación<br>    var activo bool             // Declaración con<br>    activo = true               // Posterior asignación de valor<br>    nombre := &quot;Orlando&quot;         // Declaración corta</pre><pre>fmt.Println(&quot;variables&quot;)<br>    fmt.Println(&quot;edad:&quot;, edad)<br>    fmt.Println(&quot;estatura:&quot;, estatura)<br>    fmt.Println(&quot;nombre&quot;, nombre)<br>    fmt.Println(&quot;activo&quot;, activo)<br>}</pre><p>Existen diferentes maneras de declarar las variables, como pueden ver, es posible asignar un valor en al momento de declarar la variable, también puede omitirse el tipo si el compilador es capaz de inferirlo, aunque en ocasiones es recomendable ser explícito, también puede solo declarar y posteriormente asignar un valor y, mi opción favorita, la declaración corta; con esta última es posible omitir la palabra reservada var y el tipo de variable, este se infiere del elemento que se esté asignando. Es importante resaltar que la declaración corta requiere usar := y que solamente puede usarse dentro de funciones, en el ámbito global es necesario el uso de var.</p><h3>Funciones</h3><p>En este punto deben haber visto la función main hasta el cansancio, además de la función Println perteneciente al paquete fmt. Ahora hablemos de las funciones que podemos declarar.</p><pre>package main</pre><pre>import &quot;fmt&quot;</pre><pre>func saludar(nombre string, edad int) string {<br>    return fmt.Sprintf(&quot;Hola, mi nombre es %s y tengo %d años&quot;, nombre, edad)<br>}</pre><pre>func main() {<br>    fmt.Println(saludar(&quot;Orlando&quot;, 26))<br>}</pre><p>Nótese un par de cosas: No soy muy creativo para los ejemplos, las funciones se declaran comenzando con la palabra reservada func, pueden recibir argumentos, los cuales requieren ser declarados dentro de los paréntesis de la función junto a su tipo, de igual forma, en caso de retornar un valor (o varios), se debe especificar el tipo que este tendrá después del paréntesis de cierre y antes de la llave de apertura. El retorno, como en la mayoría de los lenguajes de programación se especifica por medio de la palabra reservada return.</p><p>Sinceramente he dejado mucho material por fuera, tipos de variables, características de las funciones entre otras cosas, sin embargo, me parece que hasta este punto se satisface el objetivo del artículo, ser una pequeña introducción al lenguaje. Continuaré realizando publicaciones sobre el tema, pero si desean profundizar, les recomiendo el <a href="https://tour.golang.org/">gotour</a> en el sitio oficial del lenguaje, así como la <a href="https://golang.org/doc/">documentación</a> del mismo, que es fácil de seguir y eso se agradece. Finalmente, también recomiendo este <a href="https://www.youtube.com/watch?v=lodF5BaZdDY&amp;index=2&amp;list=PLl_hIu4u7P64MEJpR3eVwQ1l_FtJq4a5g">tutorial</a>. Saludos y hasta la próxima.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f6b3cbc96ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[De Python a Go (Golang)]]></title>
            <link>https://medium.com/@orlmonteverde/de-python-a-go-golang-7e4a14077f08?source=rss-fe146a4dcdc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e4a14077f08</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Orlando Monteverde]]></dc:creator>
            <pubDate>Mon, 19 Nov 2018 14:36:01 GMT</pubDate>
            <atom:updated>2019-04-13T20:57:39.858Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*W9-eC6Q-HUQ7GY97iIt7cA.jpeg" /></figure><p>Debo aclarar que mi objetivo no es establecer cuál es mejor o peor porque, como sucede con cualquier herramienta, si se usa para lo que fue hecha y como se debe se pueden obtener resultados asombrosos. Hablemos un poco de mi experiencia con estos lenguajes de programación, <a href="https://www.python.org/"><strong>Python</strong></a> es el primer lenguaje que aprendí y con el que comencé mi aventura en el mundo de la programación por lo que le tengo gran estima, aunque en el camino conocí y use muchos otros. Es un lenguaje interpretado y de tipado dinámico, esas características son vistas como ventajas o desventajas según a quién le preguntes, especialmente por motivos de performance. Por otra parte, <a href="https://golang.org/"><strong>Go</strong></a> es un lenguaje compilado y de tipado estático.</p><p>Ambos son de propósito general y multiparadigma, poseen una extensa librería estándar, son de código abierto, cuentan con una fuerte comunidad y mucha documentación. Sinceramente <strong>Go</strong>, por algunas características muy propias del lenguaje, no lo recomendaría para comenzar en la programación, a diferencia de <strong>Python</strong>, pero me parece un excelente segundo lenguaje. Bueno, mucho texto, veamos el código.</p><h3>El popular hola mundo</h3><p>Es casi obligatorio comenzar con un “Hola mundo” cuando estamos conociendo un nuevo lenguaje de programación y no pude resistirme a iniciar con uno.</p><h4>Con Go</h4><pre>package main</pre><pre>import &quot;fmt&quot;</pre><pre>func main() {<br>    // Este es un hola mundo en Go<br>    fmt.Println(&quot;Hola mundo&quot;)<br>}</pre><h4>Con Python</h4><pre># Este es un hola mundo en Python<br>print(&quot;Hola mundo&quot;)</pre><h3>Variables y Funciones</h3><h4>Con Go</h4><pre>package main</pre><pre>import &quot;fmt&quot;</pre><pre>func saludar(name string) string {<br>    return &quot;hola &quot; + name<br>}</pre><pre>func main() {<br>    var nombre = &quot;Orlando&quot;<br>    fmt.Println(saludar(nombre))<br>}</pre><h4>Con Python</h4><pre>def saludar(nombre):<br>    return &quot;Hola &quot; + nombre</pre><pre>nombre = &quot;Orlando&quot;<br>print(saludar(nombre))</pre><p>La diferencia más notable en lo que a sintaxis se refiere es que <strong>Go</strong> usa llaves para los bloques de código mientras que <strong>Python</strong> lo hace mediante Indentación. Además del uso de la palabra reservada <em>var</em> para declarar una variable en <strong>Go</strong>. Dejando esos detalles de lado, ambos tienen una sintaxis bastante agradable a la vista, muy legible y, por experiencia, hacen del escribir código una experiencia placentera.</p><p>Como mencioné anteriormente, ambos cuentan con una gran comunidad, por lo que existe una enorme cantidad de librerías/paquetes libres para estudiar y utilizar. Además de herramientas que facilitan la instalación de dichos paquetes, como es el caso de <em>pip</em> para <strong>Python</strong> o el comando <em>get</em> en <strong>Go</strong>, he aquí un pequeño ejemplo: pip install flask y go get github.com/labstack/echo .</p><p>Por si tienen curiosidad, en el ejemplo anterior el comando, en cada caso, permite instalar un framework web para el respectivo lenguaje. Sí, ambos suelen utilizarse para el desarrollo web del lado del servidor, pero ese es un tema para otra ocasión.</p><p>Por ahora nos concentraremos en las principales razones por las que algunas personas se quejan de los lenguajes. En el caso de <strong>Python</strong>, se suele decir que es lento: no voy a negar eso, se trata de un lenguaje interpretado, es lento comparado con otros lenguajes como C, aunque hay muchos factores a tomar en cuenta y varias alternativas para mejorar el performance (véase <a href="https://pypy.org/">PyPy</a>), no las estoy considerando para esta comparación. Debo añadir que para el uso que le he dado el lenguaje siempre me ha parecido lo suficientemente rápido en ejecución, e increíblemente ágil en los que respecta al desarrollo.</p><p>Ahora vayamos con <strong>Go</strong>, la principal queja que he escuchado/leído es que no es orientado a objetos: según <a href="https://es.wikipedia.org/wiki/Go_(lenguaje_de_programaci%C3%B3n)">Wikipedia</a><a href="https://es.wikipedia.org/wiki/Go_(lenguaje_de_programaci%C3%B3n)),">,</a> y estoy de acuerdo, si es un lenguaje orientado a objetos, sólo que de una manera bastante <em>particular</em>.</p><blockquote>Go admite el paradigma de programación orientada a objetos, pero a diferencia de los lenguajes de programación más populares no dispone de herencia de tipos y tampoco de palabras clave que denoten claramente que soporta este paradigma.</blockquote><blockquote><a href="https://es.wikipedia.org/wiki/Go_(lenguaje_de_programaci%C3%B3n)">Wikipedia</a></blockquote><h3><em>Orientación a Objetos</em></h3><h4>Con Go</h4><pre>package main</pre><pre>import &quot;fmt&quot;</pre><pre>type Persona struct {<br>    Nombre string<br>    Edad   int<br>    Activo bool<br>}</pre><pre>func (p Persona) presentarse() {<br>    if p.Activo {<br>        fmt.Printf(&quot;Hola, mi nombre es %s y tengo %d años\n&quot;, p.Nombre, p.Edad)<br>    }<br>}</pre><pre>func main() {<br>    persona := Persona{&quot;Orlando&quot;, 26, true}<br>    persona.presentarse()<br>}</pre><h4>Con Python</h4><pre>class Persona:</pre><pre>    def __init__(self, nombre, edad, activo):<br>        self.nombre = nombre<br>        self.edad = edad<br>        self.activo = activo</pre><pre>    def presentarse(self):<br>        if self.activo:<br>            print(&quot;Hola, mi nombre es {} y tengo {} años&quot;.format(<br>                self.nombre, self.edad))</pre><pre>persona = Persona(&quot;Orlando&quot;, 26, True)<br>persona.presentarse()</pre><p>Como pueden ver es más una cosa de <em>pensar diferente</em>, las estructuras no son clases pero cubren bastante bien las necesidades una vez que te acostumbras a ellas. En lo que a mi respecta, decidí pasarme completamente a <strong>Go</strong>, aún tengo mucho que aprender, pero eso no hace más que incrementar mi motivación. No lo hago porque sea mejor que <strong>Python</strong>, simplemente me parece más adecuado para mis actuales intereses.</p><p>He usado muchos lenguajes en menor o mayor medida, y puedo decir que algunos me han gustado más que otros, eso no los hace mejores o peores a menos que los compares en un contexto específico. Es decir, puede que el martillo sea tu herramienta favorita, pero algunas veces lo que necesitas hacer es aflojar una tuerca, espero me entiendan. Mi intención es que este sea el primero de una serie de artículos dedicados al lenguaje <strong>Go</strong>, me gustaría conocer su opinión. ¡Las críticas son bienvenidas! especialmente las constructivas.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e4a14077f08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Channels en Go (Golang)]]></title>
            <link>https://medium.com/@orlmonteverde/channels-en-go-golang-6f3599d92f73?source=rss-fe146a4dcdc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f3599d92f73</guid>
            <category><![CDATA[programación]]></category>
            <category><![CDATA[español]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Orlando Monteverde]]></dc:creator>
            <pubDate>Tue, 06 Nov 2018 13:59:45 GMT</pubDate>
            <atom:updated>2018-12-15T16:23:54.229Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*4D25W5vN37XoNzsexJeHFQ.png" /></figure><p><em>Ahora que conocemos las </em><a href="https://medium.com/@orlmonteverde/conociendo-las-gorutinas-en-go-golang-6d6ea2d9b6f3"><em>goroutines</em></a><em> y el </em><a href="https://medium.com/@orlmonteverde/goroutines-y-el-waitgroup-en-go-golang-ddc7c9b0b1dc"><em>WaitGroup</em></a><em> es momento de hablar de los channels, un tipo de dato muy ligado a las Goroutines y a la concurrecia en Go</em></p><p>Un <strong>channel</strong> es un tipo de variable que permite el paso de información entre <em>gorourines</em>. Me parece la manera más sencilla de definirlo. Aunque, es posible que no quedara del todo claro, así que veamos a los <strong>channels</strong> en acción.</p><pre>package main</pre><pre>import (<br>    &quot;fmt&quot;<br>    &quot;math/rand&quot;<br>    &quot;time&quot;<br>)</pre><pre>func imprimir(ch chan string, texto string) {<br>    for {<br>        // Pasando información al channel.<br>        ch &lt;- texto<br>        // Tiempo de espera entre cada iteración.<br>        // rand.Int nos permite generar un entero de manera<br>        // aleatoria y time.Sleep requiere que la variable sea<br>        // de tipo time.Duration<br>        time.Sleep(time.Duration(rand.Int()) * time.Nanosecond)<br>    }<br>}</pre><pre>func main() {<br>    // Creando un channel de tipo string.<br>    ch := make(chan string)<br>    // Pasando el channel a dos goroutines.</pre><pre>    go imprimir(ch, &quot;primera&quot;)<br>    go imprimir(ch, &quot;segunda&quot;)</pre><pre>    // Ciclo infinito que imprime la información del channel.<br>    for {<br>        fmt.Println(&lt;-ch)<br>    }<br>}</pre><p>Comencemos por la declaración del <strong>channel</strong> ch := make(chan string), hacemos uso de la función make como hemos visto antes con los <em>maps</em> y los <em>slices</em>. Pero no declaramos un <strong>channel</strong> simplemente, especificamos además el tipo de variable que va a manejar, en este caso es de tipo <em>string</em> y este será el único tipo de dato que aceptará el <strong>channel</strong>. Sin embargo, es posible crear <strong>channels</strong> de cualquiera de los tipos vistos anteriormente, incluyendo las estructuras.</p><p>La llamada a la función imprimir no aporta nada realmente nuevo, usamos la palabra reservada go para crear una nueva <em>goroutine</em> y le pasamos el <strong>channel</strong> recientemente creado y una cadena de texto. Finalmente mandamos a imprimir el contenido del <strong>channel</strong> dentro de un ciclo infinito.</p><p>En este punto si podemos notar algo interesante, ese operador semejante a una flecha &lt;-ch. De esta forma extraemos datos del <strong>channel</strong>. Si ahora observamos la función imprimir, encontramos un caso semejante: ch &lt;- texto. Esta vez no extraemos información del <strong>channel</strong> sino que la introducimos al mismo.</p><h3>Channels de una dirección</h3><p>Un detalle interesante sobre los <strong>channels</strong> es que podemos establecer que sólo trabajen en un sentido, es decir, que exclusivamente reciban datos o los envíen. Modificando un poco la función imprimir, podemos ver la sintaxis requerida para este fin.</p><pre>...<br>func imprimir(ch chan&lt;- string, texto string) {<br>    for {<br>        ch &lt;- texto<br>        time.Sleep(time.Duration(rand.Int()) * time.Nanosecond)<br>    }<br>}<br>...</pre><p>Apenas se puede notar la diferencia, así que les diré donde deben mirar: chan&lt;-. La flecha apuntando al la palabra reservada chan indica que este <strong>channel</strong> sólo puede recibir información. Esto hace fácil deducir la sintaxis utilizada para establecer un <strong>channel</strong> que envía información: &lt;-chan.</p><h3>Cerrando un channel</h3><p>Podemos cerrar un <strong>channel</strong> haciendo uso de la función close, pasando como argumento el <strong>channel</strong> a cerrar. Por ejemplo:</p><pre>...<br>func imprimir(ch chan&lt;- string, texto string) {<br>    for i := 0; i &lt; 5; i++ {<br>        ch &lt;- texto<br>        time.Sleep(time.Duration(rand.Int()) * time.Nanosecond)<br>    }<br>    close(ch)<br>}<br>...</pre><p>Podemos ver que esta vez el ciclo es finito, por lo que se imprimirá 5 veces cada palabra antes de cerrar el <strong>ch</strong> por medio de la función close. Sin embargo, al ejecutarlo notarán que posterior a las 5 impresiones comenzarán a imprimir cadenas vacías. Finalmente, obtenemos un mensaje como esta: panic: close of closed channel.</p><p>La razón es que aunque ya está cerrado el <strong>channel</strong>, seguímos solicitando información, y este nos envía el valor <em>cero</em> del tipo de dato, en este caso, una cadena vacía. Respecto al panic, ya que estamos ejecutando la función imprimir en dos <em>goroutines</em> diferentes, la primera en concluir cerrará el <strong>channel</strong>, la otra intentará hacer los mismo, pero debido a que el <strong>channel</strong> ya se encuentra cerrado se produce el panic.</p><h3>Confirmando si un channel se encuentra cerrado</h3><p>Si queremos evitar que sucedan casos como el anterior, sería conveniente confirmar si un <strong>channel</strong> se encuentra cerrado o no antes de trabajar con él. Para este fin, podemos recurrir al segundo valor obtenido al extraer valores de un <strong>channel</strong>, un boolean que indica si el <strong>channel</strong> se encuentra abierto. Su sintaxis es la siguiente: valor, booleano := &lt;- channel. Modifiquemos el código anterior.</p><pre>...<br>func main() {<br>    ch := make(chan string)<br>    go imprimir(ch, &quot;primera&quot;)<br>    go imprimir(ch, &quot;segunda&quot;)<br>    for {<br>        valor, ok := &lt;-ch<br>        if !ok {<br>            break<br>        }<br>        fmt.Println(valor)<br>    }<br>}</pre><p>Ahora confirmamos si el <strong>channel</strong> se encuentra cerrado y terminamos el ciclo. Con esto la ejecución del programa finaliza una vez que el <strong>channel</strong> se encuentra cerrado. Otra manera de hacer esto, y una que me gusta más, es usar el <em>for-range</em>.</p><pre>...<br>for valor := range ch {<br>    fmt.Println(valor)<br>}<br>...</pre><p><em>Originally published at </em><a href="https://steemit.com/cervantes/@orlmicron/channels-en-go-golang"><em>steemit.com</em></a><em> on November 6, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f3599d92f73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Goroutines y el WaitGroup en Go (Golang)]]></title>
            <link>https://medium.com/@orlmonteverde/goroutines-y-el-waitgroup-en-go-golang-ddc7c9b0b1dc?source=rss-fe146a4dcdc0------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddc7c9b0b1dc</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[programación]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[español]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Orlando Monteverde]]></dc:creator>
            <pubDate>Wed, 24 Oct 2018 19:47:21 GMT</pubDate>
            <atom:updated>2018-12-15T16:00:19.623Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*4D25W5vN37XoNzsexJeHFQ.png" /></figure><p><em>No hace mucho tiempo conocimos las </em><a href="https://medium.com/@orlmonteverde/conociendo-las-gorutinas-en-go-golang-6d6ea2d9b6f3"><em>gorutinas</em></a><em>, una manera bastante sencilla que usa </em><strong><em>Go</em></strong><em> para trabajar programas concurrentes, siendo esta una de las características más atractivas del lenguaje consideré adecuado compartir unas par de cosas más sobre ellas con ustedes.</em></p><p>Como he mencionado en varias ocasiones, la biblioteca estándar de <strong>Go</strong> es bastante amplia, nos provee de un gran número de herramientas muy útiles para diversos propósitos. El manejo de <em>goroutines</em> no podía ser la excepción. Vamos a partir de el último ejemplo de la <a href="https://medium.com/@orlmonteverde/conociendo-las-gorutinas-en-go-golang-6d6ea2d9b6f3">publicación pasada</a>.</p><pre>package main</pre><pre>import (<br>    &quot;fmt&quot;<br>    &quot;time&quot;<br>)</pre><pre>func saludar(nombres []string) {<br>    for _, nombre := range nombres {<br>        fmt.Printf(&quot;Hola %s\n&quot;, nombre)<br>        time.Sleep(1 * time.Second)<br>    }<br>}</pre><pre>func despedir(nombres []string) {<br>    for _, nombre := range nombres {<br>        fmt.Printf(&quot;Adios %s\n&quot;, nombre)<br>        time.Sleep(1 * time.Second)<br>    }<br>}</pre><pre>func main() {<br>    nombres := []string{&quot;Orlando&quot;, &quot;Daniela&quot;, &quot;José&quot;, &quot;Carlos&quot;,<br>        &quot;Andrea&quot;, &quot;David&quot;, &quot;Carmen&quot;}</pre><pre>    go saludar(nombres)<br>    go despedir(nombres)</pre><pre>    var s string<br>    fmt.Scan(&amp;s)<br>}</pre><p>No explicaré lo que este código hace, si tienes problemas para entenderlo te recomiendo leer primero <a href="https://medium.com/@orlmonteverde/conociendo-las-gorutinas-en-go-golang-6d6ea2d9b6f3">esta publicación</a>, aqu te espero. Aclarado eso, hagamos algunas modificaciones.</p><pre>package main</pre><pre>import (<br>    &quot;fmt&quot;<br>    &quot;sync&quot;<br>    &quot;time&quot;<br>)</pre><pre>// Espera que una colección de goroutines se ejecute<br>var wg sync.WaitGroup</pre><pre>func saludar(nombres []string) {<br>    // Disminuye en uno la cantidad de goroutines a esperar<br>    defer wg.Done()</pre><pre>    for _, nombre := range nombres {<br>        fmt.Printf(&quot;Hola %s\n\r&quot;, nombre)<br>        time.Sleep(1 * time.Second)<br>    }<br>}</pre><pre>func despedir(nombres []string) {<br>    // Disminuye en uno la cantidad de goroutines a esperar<br>    defer wg.Done()</pre><pre>    for _, nombre := range nombres {<br>        fmt.Printf(&quot;Adiós %s\n\r&quot;, nombre)<br>        time.Sleep(1 * time.Second)<br>    }<br>}</pre><pre>func main() {<br>    // Añade la cantidad de goroutines a esperar<br>    wg.Add(2)</pre><pre>    nombres := []string{&quot;Orlando&quot;, &quot;Daniela&quot;, &quot;José&quot;, &quot;Carlos&quot;,<br>        &quot;Andrea&quot;, &quot;David&quot;, &quot;Carmen&quot;}</pre><pre>    go saludar(nombres)<br>    go despedir(nombres)</pre><pre>    // Espera hasta que se ejecuten las goroutines<br>    wg.Wait()<br>    fmt.Println(&quot;Fin del programa&quot;)<br>}</pre><p>Gracias a las estructura WaitGroup del paquete <a href="https://godoc.org/sync">sync</a> podemos definir una colección de <em>goroutines</em> cuya ejecución debe ser esperada antes de continuar con el proceso. Por medio del método Add indicamos la cantidad de <em>goroutines</em> a esperar, el método Done indica que una <em>goroutine</em> ha concluido y se resta del grupo de espera.</p><p>No debería ser necesario explicar porque está siendo llamado en un defer, pero igual lo haré, de esa forma nos aseguramos de que se ejecute al final de la función, no está directamente relacionado con las <em>goroutines</em>, y pudo omitirse, pero me parece más legible así.</p><p>Finalmente, el método Wait obliga a esperar la ejecución del número de <em>goroutines</em> indicadas. Por tal motivo, la sentencia fmt.Println(&quot;Fin del programa&quot;) se ejecutará después de que ambas <em>goroutines</em> concluyan su ejecución.</p><p><em>Originally published at </em><a href="https://steemit.com/cervantes/@orlmicron/goroutines-y-el-waitgroup-en-go-golang"><em>steemit.com</em></a><em> on October 24, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddc7c9b0b1dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>