Step 1: Setting Up the Project
Start by creating a file namedmain.go. Define your package and main function as shown below:
Step 2: Exploring the HTTP Package
To familiarize yourself with the HTTP package, you can use a command-line utility (in our case, “KodeKloud http”) to locate relevant documentation:ListenAndServe method initializes an HTTP server. It listens on a specified TCP address and uses a handler to process incoming requests.
Step 3: Registering Handlers
Below is a sample code snippet that demonstrates how to register handlers for different URL patterns:ListenAndServe function by running:
ListenAndServe listens on the specified TCP network address and invokes the given handler to serve incoming requests. In cases where the handler is nil, the DefaultServeMux is used:
The
DefaultServeMux is an HTTP request multiplexer that matches incoming request URLs against registered patterns and invokes the appropriate handler.Step 4: Starting the HTTP Server
Initially, set up your HTTP server with a default address (usinglocalhost on port 10000) and a nil handler. Later, you will register your custom endpoints. The basic server code looks like this:
Step 5: Creating the Homepage Endpoint
To serve a homepage, register a function viaHandleFunc that handles requests to the root URL. According to the documentation, HandleFunc registers the handler function within the DefaultServeMux.
homepage function. This function accepts an http.ResponseWriter and an *http.Request. It uses fmt.Fprintf to write a formatted response back to the client:
The
fmt.Fprintf function writes formatted output to a given writer (w in this case). It returns the number of bytes written along with any error encountered.localhost:10000. Accessing the homepage in a web browser will display “Welcome to homepage”, and the server console logs:
/ to /foo, only the /foo endpoint will be active, demonstrating that only registered endpoints produce an output.
Complete Example
Below is the full example of a simple API server with a registered homepage endpoint:Conclusion
You have successfully set up a basic RESTful API server in Go. You now know how to register handlers, serve endpoints, and use Go’s HTTP package effectively. In future lessons, we will add more functionalities and expand our API by introducing additional endpoints and middleware.