In this article, we will discuss how you can create a simple HTTP server in Go. This will help you get familiar with the net/http package.
Required Imports
For us to create a HTTP server in Go, we will need to import the net/http package. It provides us with methods to implement a HTTP server with ease.
Golang Simple HTTP Server
The first step when creating a HTTP server is to determine the HTTP endpoints. For example, if a client accesses the route, http://localhost:8080/echo, what should happen?
We do this by creating a HTTP handler function. This tells the server what function to execute when a client hits the specified endpoint.
An example code is as shown below:
import "net/http"
func main() {
// define http handler for /hi
http.HandleFunc("/hi", sayHi)
}
The example above uses the http.HandleFunc() to specify which function to run when the client hits the /hi endpoint.
The next step is to define the method sayHi(). This function contains the code we wish to run when the client accesses /hi.
In our example, it is a simple “Hello” message. We can do this as shown in the code below:
fmt.Fprintf(w, "Hi")
}
The function takes two arguments:
- The writer of type http.ResponseWriter which allows you to send data to the HTTP client.
- The reader of type http.Request which holds the data structure for the HTTP Request from the client.
The function then returns a message using the Fprintf method.
The final step is to start the listener. We do this in the main function as shown in the example code below:
if err != nil {
log.Fatal(err)
return
}
The function serves the server in the specified port address. For example, in the code above, we run the server on port 8080.
By now, you should have a HTTP server that accepts request to a specific endpoint and returns a message.
The full code is as shown:
import (
"fmt"
"log"
"net/http"
)
func main() {
// define http handler for /hi
http.HandleFunc("/hi", sayHi)
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal(err)
return
}
}
func sayHi(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hi")
}
Now, we can run the server as:
With the web server running, open your HTTP client (browser) and navigate to the following endpoint.
The server should respond with a message “Hi”
Conclusion
Using this guide, you are in a position to build a HTTP server using the Go net/http package. Feel free to expand the server above and check the documentation to learn more.
Thanks for reading!