create a server in go

To create a server in Go, we first need to import the necessary packages. The net/http package provides the foundation for building HTTP servers, while the fmt package is used for printing to the console.

main.go
import (
    "fmt"
    "net/http"
)
36 chars
5 lines

Once we've imported the necessary packages, we can start defining our server. We'll create a simple server that listens on port 8080 and returns "Hello, World!" when we visit http://localhost:8080 in a web browser.

main.go
func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello, World!")
    })

    http.ListenAndServe(":8080", nil)
}
174 chars
8 lines

The http.HandleFunc() function takes two arguments: a path (in this case, /) and a function that will be called when that path is visited. The function takes two arguments: a http.ResponseWriter, which is used to write the response back to the client, and a pointer to a http.Request, which contains information about the incoming request.

Finally, we call http.ListenAndServe() to start the server. This function takes two arguments: the port to listen on (in this case, :8080), and a http.Handler. If we pass nil as the second argument, the server will use the default HTTP server.

And that's it! With these few lines of code, we've created a basic HTTP server in Go.

related categories

gistlibby LogSnag