Go in Plain English: Creating your First WebServer
Related Articles
Go in Plain English: Setting things up and Hello World!
Go in Plain English: Playing with Strings
Quick Intro
I'm the kind of guy that I need to get something done to believe I'm learning.
In this short article, I'll show you how easy it is to be up and running with a WebServer in Go.
The Code
Here's the code you need to run a very basic web server:
Code Explained
We're importing net/http which is the library that allows Go to handle HTTP requests and do something about them.
Our responder function here is used to create our HTTP response, i.e. what are we going to respond to web browser once we receive a request.
The Fprint function here is particularly useful because it formats whatever you add to second parameter and throws it into first parameter (resp).
The function responder becomes will be our response.
In the main part of the program, we call http.HandleFunc and what it does is it calls function responder if we receive an HTTP request to "/" to handle the HTTP response.
http.ListenAndServe makes sure our HTTP server is listening on port 8080.
Running our Code
I saved my code in draft.go and ran it like this:
This is what I see:
Adding more Paths
I just added an IF and an ELSE IF statements:
You need to hit Ctrl+C to stop our previous code and start it again:
But here's what we get when we go to /anotherpath:
Notice that all responses up to now are 200 OK:
If we go to anything else that is not / or /anotherpath we hit our last else statement:
Because we explicitly added http.StatusNotFound then the response is now 404:
That should be enough to get started but this library is very powerful and rich.
The documentation along with all functions are here: https://golang.org/pkg/net/http/
Optimising our Code
If your page has many paths, it's probably better to organise them into functions. In this case, we can use a router such as https://github.com/gorilla/mux but we need to follow the instructions in previous link to clone library locally so it's available to your installed Go version.
After it's all done, we can split the paths into functions and that's way more scalable than using multiple if's and else's:
The major difference here is that we need to create an instance of the router first (my router := mux.NewRouter()) and then we add the appropriate paths per function.
And finally:
Hang on! Why we didn't create a function for any other non-existing paths (404)?
Because that's the default: