create a http server in go

To create a basic HTTP server in Go, you can use the net/http package. Here is an example code that creates a server on port 8080, listens for incoming requests, and responds with "Hello, World!" for all requests:

main.go
package main

import (
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello, World!"))
    })

    http.ListenAndServe(":8080", nil)
}
216 chars
14 lines

The http.HandleFunc() function registers a callback function that will handle incoming requests to the specified route. In this case, we are handling the root route /, and responding with a simple text "Hello, World!".

The http.ListenAndServe() function starts the server and listens for incoming requests on the specified network address ":8080" (the empty nil parameter indicates to use the default ServeMux).

To test this code, you can open up a web browser and go to http://localhost:8080/ in the URL bar. The server should respond with the "Hello, World!" message.

related categories

gistlibby LogSnag