Follow

Follow
Basic Server In GoLang

Basic Server In GoLang

Gaurav Bharadwaj's photo
Gaurav Bharadwaj
·Nov 4, 2022·

2 min read

Play this article

What is a server?

A server is a machine that provides data on request, the application that channels it, and the database which organizes the information.

Project setup

create a new go project and create a file main.go.

Open the main.go file and import the required packages. We’ll use fmt to print useful data to the terminal and log to print fatal errors in case the web server crashes.

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


    fmt.Printf("Starting server at port 8080\n")
    if err := http.ListenAndServe(":8080", nil); err != nil {
        log.Fatal(err)
    }
}

The ListenAndServe method is exported by the http packet we imported during step one. This method allows us to start the web server and specify the port to listen for incoming requests.

We’ll use the HandlerFunc function to add route handlers to the web server. The first argument accepts the path it needs to listen for /hello. Here, you tell the server to listen for any incoming requests for localhost:8080/hello. The second argument accepts a function that holds the business logic to correctly respond to the request. By default, this function accepts a ResponseWriter to send a response back and a Request object that provides more information about the request itself. For example, you can access information about the sent headers, which can be useful for authenticating the request.

Start the web server with go run server.go and visit localhost:8080/hello. If the server responds with "Hello!"

Screenshot from 2022-11-02 14-18-07.png

visit our next post of the series lightweight-docker-images-why-and-how?

 
Share this