Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying Go Recipes for Developers
  • Table Of Contents Toc
  • Feedback & Rating feedback
Go Recipes for Developers

Go Recipes for Developers

By : Burak Serdar
close
close
Go Recipes for Developers

Go Recipes for Developers

By: Burak Serdar

Overview of this book

With its simple syntax and sensible conventions, Go has emerged as the language of choice for developers in network programming, web services, data processing, and other settings. This practical guide helps engineers leverage Go through up-to-date recipes that solve common problems in day-to-day programming. Drawing from three decades of distributed systems engineering and technical leadership at companies like Red Hat, Burak Serdar brings battle-tested expertise in building robust, scalable applications. He starts by covering basics of code structure, describing different approaches to organizing packages for different types of projects. You’ll discover practical solutions to engineering challenges in network programming, dealing with processes, databases, data processing pipelines, and testing. Each chapter provides working solutions and production-ready code snippets that you can seamlessly incorporate into your programs while working in sequential and concurrent settings. The solutions leverage the more recent additions to the Go language, such as generics and structured logging. Most of the examples are developed using the Go standard library without any third-party packages. By the end of this book, you’ll have worked through a collection of proven recipes that will equip you accelerate your Go development journey.
Table of Contents (20 chapters)
close
close

Using internal packages to reduce an API surface

Not every piece of code is reusable. Having a smaller API surface makes it easier for others to adapt and use your code. So, you should not export APIs that are specific to your program.

How to do it...

Create internal packages to hide implementation details from other packages. Anything under an internal package can only be imported from the packages under the package containing that internal package – that is, anything under myproject/internal can only be imported from the packages under myproject.

In our example, we placed the database access code into a package where it can be accessed by other programs. However, it does not make sense to expose the HTTP routes to others, as they are specific to this program. So, we will put them under the webform/internal package.

This is the internal/routes/routes.go file:

package routes
import (
    "database/sql"
    "github.com/gorilla/mux"
    "net/http"
)
func Build(router *mux.Router, conn *sql.DB) {
    router.Path("/form").
        Methods("GET").HandlerFunc(func(w http.ResponseWriter, r 
        *http.Request) {
        http.ServeFile(w, r, "web/static/form.html")
    })
    router.Path("/form").
        Methods("POST").HandlerFunc(func(w http.ResponseWriter, r 
        *http.Request) {
        handlePost(conn, w, r)
    })
}
func handlePost(conn *sql.DB, w http.ResponseWriter, r *http.Request) {
    email := r.PostFormValue("email")
    comment := r.PostFormValue("comment")
    _, err := conn.ExecContext(r.Context(), "insert into comments 
    (email,comment) values (?,?)",
    email, comment)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    http.Redirect(w, r, "/form", http.StatusFound)
}

Then, we change the main.go file to use the internal package:

package main
import (
    "database/sql"
    "net/http"
    "github.com/gorilla/mux"
    _ "modernc.org/sqlite"
    "github.com/PacktPublishing/Go-Recipes-for-Developers/src/chp1/
    webform/internal/routes"
    "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)
    r := mux.NewRouter()
    routes.Build(r, db)
    server := http.Server{
        Addr:    ":8181",
        Handler: r,
    }
    server.ListenAndServe()
}
Visually different images
CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
Go Recipes for Developers
notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist download Download options font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon
Modal Close icon
Modal Close icon