DEV Community

Cover image for Build a simple HTTP Server in GoLang
Akshay Rao
Akshay Rao

Posted on

Build a simple HTTP Server in GoLang

Hi this is Akshay Rao. I wanted to learn Go language, so thought of building a simple project. In this project ,I have built a simple a HTTP server which gives a html Response in the web browser when the paths are changed.

Let's Start

  1. We will have to specify the package, I am main because the package "main" instructs the Go compiler to build the package as an executable application rather than a shared library. Our executable application will launch from the "main" function in the package.
  2. Create a file name it as .go extension like I have named as “project.go”.
  3. GoLang has packages for all the commands, so we will have to import packages
.
  4. fmt- will help in printing out the results and getting inputs from users.
  5. - html - to print the html response on the web browser.

  6. - log- if there is any error while running the serverit will log the error in terminal.

  7. - net/http - to create a server.
  8. Create a function main.
  9. Call the HandlerFunc from the http api, which will call the function specified in it fro the specified path.
  10. At last we will run the server with the help of ListenAndServe at 8080 and set the error message as nil.
  11. Wrap the ListenAndServe in log.Fatal to the show the error if it occurs.
  12. Then run “go run /folder name/.go”

Image 1
Open localhost:8080 in your web browser

Image 2
Add /home to the url

Image 3
Thank you

Top comments (0)