Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Go CookBook

You're reading from   Go CookBook Top techniques and practical solutions for real-life Go programming problems

Arrow left icon
Product type Paperback
Published in Dec 2024
Publisher Packt
ISBN-13 9781835464397
Length
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Burak Serdar Burak Serdar
Author Profile Icon Burak Serdar
Burak Serdar
Arrow right icon
View More author details
Toc

Table of Contents (20) Chapters Close

Preface 1. Chapter 1: Project Organization 2. Chapter 2: Working with Strings FREE CHAPTER 3. Chapter 3: Working with Date and Time 4. Chapter 4: Working with Arrays, Slices, and Maps 5. Chapter 5: Working with Types, Structs, and Interfaces 6. Chapter 6: Working with Generics 7. Chapter 7: Concurrency 8. Chapter 8: Errors and Panics 9. Chapter 9: The Context Package 10. Chapter 10: Working with Large Data 11. Chapter 11: Working with JSON 12. Chapter 12: Processes 13. Chapter 13: Network Programming 14. Chapter 14: Streaming Input/Output 15. Chapter 15: Databases 16. Chapter 16: Logging 17. Chapter 17: Testing, Benchmarking, and Profiling 18. Index 19. Other Books You May Enjoy

Importing third-party packages

Most projects will depend on third-party libraries that must be imported into them. The Go module system manages these dependencies.

How to do it...

  1. Find the import path of the package you need to use in your project.
  2. Add the necessary imports to the source files you use in the external package.
  3. Use the go get or go mod tidy command to add the module to go.mod and go.sum. If the module was not downloaded before, this step will also download the module.

Tip

You can use https://pkg.go.dev to discover packages. It is also the place to publish documentation for the Go projects you publish.

Let’s add a database to our program from the previous section so that we can store the data submitted by the web form. For this exercise, we will use the SQLite database.

Change the cmd/webform/main.go file to import the database package and add the necessary database initialization code:

package main
import (
    "net/http"
    "database/sql"
    _ "modernc.org/sqlite"
    "github.com/PacktPublishing/Go-Recipes-for-Developers/src/chp1/
    webform/pkg/commentdb"
)
func main() {
    db, err := sql.Open("sqlite", "webform.db")
    if err != nil {
        panic(err)
    }
    commentdb.InitDB(db)
    server := http.Server{
        Addr:    ":8181",
        Handler: http.FileServer(http.Dir("web/static")),
    }
    server.ListenAndServe()
}

The _ "modernc.org/sqlite" line imports the SQLite driver into the project. The underscore is the blank identifier, meaning that the sqlite package is not directly used by this file and is only included for its side effects. Without the blank identifier, the compiler would complain that the import was not used. In this case, the modernc.org/sqlite package is a database driver, and when you import it, its init() functions will register the required driver with the standard library.

The next declaration imports the commentdb package from our module. Note that the complete module name is used to import the package. The build system will recognize the prefix of this import declaration as the current module name, and it will translate it to a local filesystem reference, which, in this case, is webform/pkg/commentdb.

On the db, err := sql.Open("sqlite", "webform.db") line, we use the database/sql package function, Open, to start a SQLite database instance. sqlite names the database driver, which was registered by the imported _ "modernc.org/sqlite".

The commentdb.InitDB(db) statement will call a function from the commentdb package .

Now, let’s see what commentdb.InitDB looks like. This is the webform/pkg/commentdb/initdb.go file:

package commentdb
import (
    "context"
    "database/sql"
)
const createStmt=`create table if not exists comments (
email TEXT,
comment TEXT)`
func InitDB(conn *sql.DB) {
    _, err := conn.ExecContext(context.Background(), createStmt)
    if err != nil {
        panic(err)
    }
}

As you can see, this function creates the database tables if they have not been created yet.

Note the capitalization of InitDB. If the first letter of a symbol name declared in a package is a capital letter, that symbol is accessible from other packages (i.e., it is exported). If not, the symbol can only be used within the package it is declared (i.e., it is not exported). The createStmt constant is not exported and will be invisible to other packages.

Let’s build the program:

$ go build ./cmd/webform
  cmd/webform/main.go:7:2: no required module provides package modernc.org/sqlite; to add it:
      go get modernc.org/sqlite

You can run go get modernc.org/sqlite to add a module to your project. Alternatively, you can run the following:

$ go get

That will get all the missing modules. Alternatively, you can run the following:

$ go mod tidy

go mod tidy will download all missing packages, update go.mod and go.sum with updated dependencies, and remove references to any unused modules. go get will only download missing modules.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image