[golang] Create a simple HTTP Server with golang
Creating a simple HTTP Server is quite easy with go, with a few lines of code to achieve this. Following up on our earlier blog on “Writing a simple application with golang” this post will guide you through the steps taken to create this service. Assuming the environment is setup and ready will go straight into business.
Writing a simple HTTP Server
We need to import 2 packages to do this;
import "fmt" import "net/http"
Now, Create the handler which will be handling the incoming request; Here, we will be just printing “It’s Alive!!!”
func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "It's Alive!!!") }
Now, Create the main function where it listens through port 8000 and redirect traffic coming into “/” to the created handler
func main() { http.HandleFunc("/", handler) http.ListenAndServe(":8000", nil) }
and that’s it!.
The full code block is as below;