How to Run HTTP Server in Go
Go has a built-in webserver. In this tutorial, I’m going to show how to run the HTTP server in Go.
Table of Contents
Step 1 : Create Project & Import Packages
At first, create a project and under the project create a file called http-server.go. We need to import fmt and net/http packages:
import (
"fmt"
"net/http"
)Step 2 : Create Request Handler
After that, we need to create an HTTP request handler function. The syntax:
func (w http.ResponseWriter, r *http.Request)The http.ResponseWriter contains text/html & http.Request contains all HTTP requests such as headers/URL.
Let’s create a function called hello as an HTTP handler function:
func hello(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "Hello world, Welcome to MyNotePaper!")
}From the main() function we need to call this function like:
http.HandleFunc("/", hello)Step 3 : Listen HTTP Connections
Using ListenAndServe() function, we’re able to open port to listen HTTP. We need to write this function in main() function. Let’s run this project on 80 port:
http.ListenAndServe(":80", nil)Now run go run http-server.go command and go to the browser & visit http://localhost/ to see the contents.
Step 4 : The Full Code
The final code of this simple project:
package main
import (
"fmt"
"net/http"
)
func hello(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "Hello world, Welcome to MyNotePaper!")
}
func main() {
// route
http.HandleFunc("/", hello)
// listen port 80
http.ListenAndServe(":80", nil)
}We’re done. I hope this article will help you.
Md Obydullah
Software Engineer | Ethical Hacker & Cybersecurity...
Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.