DEV Community

Cover image for Writing Go with Github Copilot
Tarek Ali
Tarek Ali

Posted on

Writing Go with Github Copilot

Intro

I've been using Github Copilot a lot recently. In fact, my latest project, redisql, was written partially with suggested code snippets. In this post, I'll illustrate its power with various examples.

Examples

We'll start with simple arithmetic, then advance to web servers and SQL transactions.

Math

// Write a function that returns the square of the number.
func square(a int) int {
    return a * a
}
Enter fullscreen mode Exit fullscreen mode

Now for something more advanced:

// Write a function that multiples two two-dimensional arrays together and returns the result.
func multiply(a [][]int, b [][]int) [][]int {
    result := make([][]int, len(a))
    for i := range result {
        result[i] = make([]int, len(a[i]))
        for j := range result[i] {
            result[i][j] = a[i][j] * b[i][j]
        }
    }
    return result
}
Enter fullscreen mode Exit fullscreen mode

Web

// Write an http server which returns 'hello world' for any request.
package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, "hello world")
    })
    http.ListenAndServe(":8080", nil)
}
Enter fullscreen mode Exit fullscreen mode

At this point I attempted requesting html rendering with user data. Needless to say, copilot crushed it, even commenting in instructions on how to run the program:

// Write an http web server that returns an html header that shows the user's IP address and the time.
// Usage:
// go run examples/web/httpserverwithhtml.go
package main

import (
    "fmt"
    "net/http"
    "time"
)

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

func handler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "text/html; charset=utf-8")
    fmt.Fprintf(w, "<html><body><h1>Your IP is %s. The time is %s</h1></body></html>",
        r.RemoteAddr, time.Now().Format(time.RFC1123))
}
Enter fullscreen mode Exit fullscreen mode

I attempted requesting something even more advanced: a WebSocket server that echoes whatever is sent to it with HTML input. Sadly, copilot couldn't handle this task, and suggested incomplete code. Over time, with more training, this may be possible.

SQL

// Write a program that opens a MySQL server connection and executes a query on a user table and prints the results.
package main

import (
    "database/sql"
    "fmt"
    "log"

    _ "github.com/go-sql-driver/mysql"
)

func main() {
    // Open a connection to the MySQL server
    db, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/test")
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    // Execute a query
    rows, err := db.Query("SELECT * FROM user")
    if err != nil {
        log.Fatal(err)
    }
    defer rows.Close()

    // Loop through the rows and print the results
    for rows.Next() {
        var id int
        var name string
        if err := rows.Scan(&id, &name); err != nil {
            log.Fatal(err)
        }
        fmt.Println(id, name)
    }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Copilot is extremely helpful. The snippets are only basic examples of its capacity, I am actively posting more in go-copilot.

Discussion (2)

Collapse
robinhuiser profile image
Robin Huiser

Hi,

Thanks for the article - it made me interested in Github Copilot!

As a minor suggestion, it would have been good if you would link or describe in your article what Github Copilot is (not everyone knows for sure) and provide an example of how you were able to integrate this in your environment (VSCode?).

That would definitely move this article from "great " to awesome!

Robin

Collapse
tarekali profile image
Tarek Ali Author

Thanks for the feedback, Robin. I’ll try doing this later today. I don’t want it to break the semantic flow of the article though; shouldn’t be much of an issue.