Simple HTTP Server in Golang

clock icon

Asked 6 months ago

message icon

1

eye icon

22

How does Golang differ from JavaScript in backend development...?

1 Answer

To create a simple HTTP server in Go (Golang), you can use the built-in net/http package. Here's a basic example:

1package main
2
3import (
4 "fmt"
5 "net/http"
6)
7
8func handler(w http.ResponseWriter, r *http.Request) {
9 fmt.Fprintf(w, "Hello, World!")
10}
11
12func main() {
13 http.HandleFunc("/", handler)
14 http.ListenAndServe(":8080", nil)
15}
1package main
2
3import (
4 "fmt"
5 "net/http"
6)
7
8func handler(w http.ResponseWriter, r *http.Request) {
9 fmt.Fprintf(w, "Hello, World!")
10}
11
12func main() {
13 http.HandleFunc("/", handler)
14 http.ListenAndServe(":8080", nil)
15}

Explanation:

  • Package Import: We import fmt for formatting and net/http for HTTP server functionalities.
  • Handler Function: The handler function writes "Hello, World!" to the response.
  • Main Function: We set up the route and start the server on port 8080.

Differences from JavaScript in Backend Development:

  • Concurrency: Go has built-in support for concurrency with goroutines, making it easier to handle multiple requests simultaneously compared to JavaScript's event-driven model.
  • Static Typing: Go is statically typed, which can help catch errors at compile time, while JavaScript is dynamically typed.
  • Performance: Go generally offers better performance for CPU-bound tasks due to its compiled nature.

This simple server is a great starting point for understanding how to build web applications in Go!

1

Write your answer here