A Quick Start Guide of HTTP Server Using Go
In this article, take a look at a quick start guide of HTTP Server using Go.
Join the DZone community and get the full member experience.
Join For FreeWhy We Need to Know HTTP Request and Response
Data is being shared with many software that could be web applications or mobile applications to visualize and make an impact. HTTP is the most popular and robust way to expose the data to different kinds of applications.
Install Go
In case you don't have Go installed in your local machine, download the binary release suitable for your system.
After downloading the package, open and follow the instructions, then go to the distribution file, which should be installed to /usr/local/go.
Now set the PATH of Go distribution to make the Go command available.
export PATH=$PATH:/usr/local/go/bin
Create HTTP Server
In Go, it's just like magic to start an HTTP server where you just need to import "net/http" package and define the HTTP listen to port and server. Paste the following code into your first server.go file and save it.
xxxxxxxxxx
package main
import (
"net/http"
)
func main() {
http.ListenAndServe(":8080", nil)
}
Navigate to your working server.go file directory and build and run your go sever $ go run server.go
Paste the following URL into your browser and hit enter.
xxxxxxxxxx
http://localhost:8080/
You should be able to see the following in your browser:
xxxxxxxxxx
404 page not found
404 is expected here because we have not created the /(root) handler yet. The new version of your server.go is the following:
x
package main
import (
"fmt"
"net/http"
)
func main() {
const PORT = 8080
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "This is simple http request handler")
})
http.ListenAndServe(fmt.Sprintf(":%d", PORT), nil)
}
Type the following URL on your browser
xxxxxxxxxx
http://localhost:8080/
This time you should be able to see the following response in your browser:
xxxxxxxxxx
This is simple http request handler
Hope this helped!
Opinions expressed by DZone contributors are their own.
Comments