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 web server


In this section, we're going to see how to create a simple web server in Go. It is really easy to create a simple web server in Go due to the built-in API. To begin, we are going to use the net/http package. A net/http package has the HandleFunc() method, which means that it will accept two things. The first is the path of the URL, and the second is the function that you want to handle incoming requests with. Check the following code:

package main
import "net/http"
func sayHello(w http.ResponseWriter, r *http.Request){
  w.Write([]byte("Hello, world"))
}
func main(){
  http.HandleFunc("/", sayHello)
  err := http.ListenAndServe(":5050", nil)
  if(err != nil){
    panic(err)
  }
}

As long as your method signature satisfies the func sayHello(w http.ResponseWriter, r *http.Request){} type of method, it will be accepted by our HandleFunc(). We will use sayHello as our function and it'll return two things, firstly, http.ResponseWriter, while the second thing is the...