DEV Community

Cover image for Simple Golang HTTP server example
Onelinerhub
Onelinerhub

Posted on

1 1

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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

AWS GenAI Live!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️