Continuing with our #golang-tutorial blog series, in this post we will setup a Basic HTTP Server in Go.
Our Web Server:
Our Web Server will respond on 2 Request Paths:
1 2 |
|
Application Code:
If you have not setup your golang environment, you can do so by visiting @AkyunaAkish’s Post on Setting up a Golang Development Enviornment on MacOSX.
Create the server.go
or any filename of your choice. Note: I created 2 ways of returning the content of http response for demonstration
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
|
Explanation of what we are doing:
- Programs runs in the package
main
- We are importing 3 packages:
io
,log
andnet/http
- HandleFunc registers the handler function for the given pattern in the DefaultServeMux, in this case the HandleFunc registers
/
to thehello
handler function and/cheers
to the goodbye handler function. - In our 2 handler functions, we have two arguments:
- The first one is
http.ResponseWriter
and its corresponding response stream, which is actually an interface type. - The second is
*http.Request
and its corresponding HTTP request.io.WriteString
is a helper function to let you write a string into a given writable stream, this is named theio.Writer
interface in Golang.
- The first one is
- ListenAndServe starts an HTTP server with a given address and handler. The handler is usually nil, which means to use DefaultServeMux
- The logging is not a requirement, but used it for debugging/verbosity
Running our Server:
Run the http server:
1
|
|
Client Side Requests:
Run client side http requests to your golang web server:
1 2 3 4 5 6 7 |
|
And another request to /cheers
:
1 2 3 4 5 6 7 |
|
Server Side Output:
As we used the log package, the logging gets returned to stdout:
1 2 3 |
|