In this lesson, we will build a simple HTTP server using the net/http
built in library
First create the directory and file
mkdir HttpServer
cd HttpServer
touch main.go
Then, use the following Go code. The code explanation is below.
package main
import (
"fmt"
"log"
"net/http"
)
const HOST = "localhost:3000"
func GetRequest(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello World")
}
func main() {
http.HandleFunc("/", GetRequest)
err := http.ListenAndServe(HOST, nil)
if err != nil {
log.Fatal("Error Starting Servier ", err)
return
}
}
And run the code with the following command.
go run main.go
We start with some set up. We simply import some needed libraries (most notably net/http). And, we declare a constant where we will have go serve requests.
package main
import (
"fmt"
"log"
"net/http"
)
const HOST = "localhost:3000"
Next, we create a function that will accept a Get http request.
We have two parameters w http.ResponseWriter
and r *http.Request
which are built into the net/http
package. We use the w http.ResponseWriter
with the fmt
library to output our text.
func GetRequest(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello World")
}
Finally, we declare a route to our request using the following.
http.HandleFunc("/", GetRequest)
This says that when a user goes to our base url (the const HOST variable), serve
them using our GetRequest
function.
Finally, we turn the server on and check for an error.
err := http.ListenAndServe(HOST, nil)
if err != nil {
log.Fatal("Error Starting Servier ", err)
return
}