My first experience running a Go web server

in #programming9 years ago (edited)

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

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

Themain.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

Sort:  

This is really interesting information thank for that. I really thinking about start working with GO.

This post recieved an upvote from minnowpond. If you would like to recieve upvotes from minnowpond on all your posts, simply FOLLOW @minnowpond

Coin Marketplace

STEEM 0.04
TRX 0.33
JST 0.076
BTC 61973.24
ETH 1625.90
USDT 1.00
SBD 0.40