Simple Golang HTTP server example

nonunicorn

Onelinerhub

Posted on July 14, 2022

Simple Golang HTTP server example

Creating HTTP server in Go is as simple as:

package main
import ( "fmt"; "net/http" )

func hi(w http.ResponseWriter, req *http.Request) {
  fmt.Fprintf(w, "Oh hi!\n")
}

func main() {
  http.HandleFunc("/hi", hi)
  http.ListenAndServe(":8222", nil)
}
Enter fullscreen mode Exit fullscreen mode

http.ListenAndServe(":8222", nil)

Here we've created simple server listening for requests on 8222 port of our machine. This is available from net/http package.

http.HandleFunc("/hi", hi)

This asks Go to handle all /hi requests with hi() function.

func hi()

This function just answers to any HTTP request with Oh hi! text. We use fmt.Fprintf to write text to http.ResponseWriter.

You might also want to know how to get client ip, query parameters values or work with request body.

💖 💪 🙅 🚩
nonunicorn
Onelinerhub

Posted on July 14, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related