Saturday 16 October 2021

How To Create HTTP Server In Golang

The HTTP services in golang isn't complex at all. The HTTP package makes it easier to write or create a HTTP services without facing an major issues as compare to other programming languages. In this post we will going to create a HTTP server with the help of the golangs' http package.


Loading The Package(net/http) We Need

Before working on the server we needed to import the http package. It contains client and server implementation of HTTP.


import "net/http"


Simple HTTP server Creation

To Create a simple HTTP server we need to create endpoints as well as. In Go, we need to use handler functions that will handles different routers whenever they are called. Here is a simple server that listens on port 8000. So the endpoint is simple which is the main index or you can say home which we denotes via this characters "/".


package main
 
import (
    "fmt"
    "net/http"
)
 
func main() {
    // handle route using handler function
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Simple http server!")
    })
 
    // listen to port
    http.ListenAndServe(":8000", nil)
}


Now let's try to access the port number 8000 with the localhost you can follow as in below

simple http server golang


The Server is Running


Creating Multiple Routes

We can creating multiple router we need, To create multiple routes we just need to provide the path and the function which is going to invoke whenever endpoints get's any hit. Let's see how to create multiple endpoints.


    package main

    import (
        "fmt"
        "net/http"
    )

    func main() {
        // handle route using handler function
        http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
            fmt.Fprintf(w, "Simple http server!")
        })

        http.HandleFunc("/about", func(w http.ResponseWriter, r *http.Request) {
            fmt.Fprintf(w, "It's About Endpoint!")
        })

        http.HandleFunc("/contact", func(w http.ResponseWriter, r *http.Request) {
            fmt.Fprintf(w, "It's Contact Endpoint!")
        })

        http.HandleFunc("/user", func(w http.ResponseWriter, r *http.Request) {
            name := r.URL.Query().Get("name")
            if name == "" {
                name = "Anonymous"
            }
            n := fmt.Sprintf("Hello %s", name)
            fmt.Fprintf(w, n)
        })

        // listen to port
        http.ListenAndServe(":8000", nil)
    }



Here we have added three more endpoints and each endpoint is printing something so let's start checking the results of endpoints one by one

When we access the about’ route we get different results.

It can be seen, that each route is handled by different handlers.

You can see at the last endpoint i have my name which is coming from backend after I have provided it into the endpoint this the called the query parameters in url. user endpoint also have one condition if the query parameter is blank or not used then the answer of the endpoint will going to be changed from name to anonymuse user let's check this result as well.

So now you guys know how we can also use qurey parameters as well from endpoint to make our output even more dynamic as per each requests.

Second Approach To Create HTTP Server

A mux is a multiplexer. Go has a type servemux defined in http package which is a request multiplexer. Here’s how we can use it for different paths. Here we are using the io package to send results.


   
   package main

    import (
        "fmt"
        "net/http"
    )

    func main() {

        mux := http.NewServeMux()

        // handle route using handler function
        mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
            fmt.Fprintf(w, "Simple http server!")
        })

        mux.HandleFunc("/about", func(w http.ResponseWriter, r *http.Request) {
            fmt.Fprintf(w, "It's About Endpoint!")
        })

        mux.HandleFunc("/contact", func(w http.ResponseWriter, r *http.Request) {
            fmt.Fprintf(w, "It's Contact Endpoint!")
        })

        mux.HandleFunc("/user", func(w http.ResponseWriter, r *http.Request) {
            name := r.URL.Query().Get("name")
            if name == "" {
                name = "Anonymous"
            }
            n := fmt.Sprintf("Hello %s", name)
            fmt.Fprintf(w, n)
        })

        // listen to port
        http.ListenAndServe(":8000", mux)
    }

If You Find It Usefull and want me to create more on it please don't forget to support me: Support Me

Labels:

0 Comments:

Post a Comment

If have any queries lemme know

Subscribe to Post Comments [Atom]

<< Home