Book Image

Hands-On Go Programming

By : Tarik Guney
Book Image

Hands-On Go Programming

By: Tarik Guney

Overview of this book

<p>With its C-like speed, simplicity, and power for a growing number of system-level programming domains, Go has become increasingly popular among programmers. Hands-On Go Programming teaches you the Go programming by solving commonly faced problems with the help of recipes. You will start by installing Go binaries and get familiar with the tools used for developing an application. Once you have understood these tasks, you will be able to manipulate strings and use them in built-in function constructs to create a complex value from two floating-point values. You will discover how to perform an arithmetic operation date and time, along with parsing them from string values. In addition to this, you will cover concurrency in Go, performing various web programming tasks, implementing system programming, reading and writing files, and honing many fundamental Go programming skills such as proper error handling and logging, among others. Whether you are an expert programmer or newbie, this book helps you understand how various answers are programmed in the Go language.</p>
Table of Contents (18 chapters)
Title Page
Copyright and Credits
Packt Upsell
Contributor
Preface
Index

Creating a simple file server


In this section, we're going to see how to create a simple file server. The main idea behind a file server is to serve static files, such as images, or CSS files, or JavaScript files, and, in our code, we're going to see how to do this. Check the following code:

package main

import "net/http"

func main() {
  http.Handle("/", http.FileServer(http.Dir("./images")))
  http.ListenAndServe(":5050", nil)
}

As you can see, we have used the HTTP handle, and this Handle is different from handleFunc and accepts a handler interface as a second parameter; the first parameter is pattern. We are going to use a special API called FileServer and it will work as a file server here; we will add a location (image directory, ./images) in the server to serve the static files.

So, what's going to happen is that when the request hits the route path, a file server will serve the requests and it will give static files under the location http.Dir("./images"). We are going to use http...