Create a web server in Go

Shakir Ck
2 min readFeb 17, 2022

Go is a popular programming language adopted by big companies and its popularity will not be going away in the near future, Go is now used in many areas including cloud-based and server-side applications. The main reason I believe it is popular is that it is said to be an easy language to learn(In my view the syntax is simple, but there are some areas you might feel difficulties with), statically typed compiled programming language.

Creating a basic HTTP server in Go is very easy, we don’t need to install anything other than the Go programming language. Go has a very powerful net/http package.

Our server will listen to the port using http.ListenAndServe, which takes 2 parameters, an address and a handler( use nil to use the DefaultServerMux).

http.ListenAndServe(":5050", nil)

http.handleFunc gives us the proper signature to register a handler. A handler takes http.ResponseWriter and an http.Request as arguments.

func homeHandler(rw http.ResponseWriter, r *http.Request) {

Then we read some data from the request using ioutil.ReadAll,

d, err := ioutil.ReadAll(r.Body)

then we will check for any error

if err != nil {log.Println(err)http.Error(rw, "oops, Something Went Wrong", http.StatusBadRequest)return
}

we are using logpackage instead of fmt. It is a simple logging package inside Go.

Then we are returning with a response, in this case, the same thing we go from the request.

rw.Header().Set("Content-Type", "application/json") 
rw.Write(d)

To start the server run

$ go run main.go

To test the server

$ curl -v -d "{name:go-server}"  localhost:5050

You should get some response in the terminal if everything runs perfectly.

--

--