My first experience running a Go web server

View this thread on: d.buzz | hive.blog | peakd.com | ecency.com
·@codero·
0.000 HBD
My first experience running a Go web server
Today, I started a code along with an online tutorial that walks me through creating a web app with go. Before everything else though, I needed to install the go environment (mac version). Following the completion of the installation process, I  set up the directory where my app would reside. If you are on a mac, a go directory is created on your home directory by default. There you will be able to create all your go apps (it will serve as your go workspace).

![golang.png](https://steemitimages.com/DQmdkSjpHyyeXwNQNWbSaCV4AcPJfveEgjCLEnFrzfQEf7H/golang.png)



 Go into the `/go` directory and create a  `src` directory. Under `src` create a directory named  `myapp` and inside create the file `main.go`.

```
/go
  /src
   /myapp
     - main.go
```




The`main.go` file is where you will write your go code in.

```
package main

import "net/http"

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("Hey!"))
	})

	http.ListenAndServe(":8000", nil)
}

```

You can see in the above I am importing the  "net/http" library to be able to do http requests. Inside the main function, I call the `HandleFunc()` method of the `http` object. This method takes two parameters, the path and a callback function that gets executed when you append that path to the url. The callback has two params that allow us to work with the request and response objects that come in and go out of the server. In the case above, we call `Write()` on `w` and pass to it the data that we want to send back to the browser.
 
There is also a `ListenAndServe`  method that gets called to specify the port number. Here our server is listening on port `8000`. 

 If you are used to running node servers, you would find running the server a little bit strange. First, you have to install the app with  the following command

```go install myapp```

Immediately after a `bin` folder is created at the root directory containing the `src` folder, where your app `myapp` resides.
If you are on mac, the next command will immediately start the server for you:

```./bin/myapp```

Now simply go to your browser and type in https://localhost:8000 in the address bar and you should see the message `Hey!` on the browser.

Follow me @codero
👍 , , , , , , , ,