building API in golang

Golang Web: Building a High-Performance APIs in Go

Golang has become a popular language for web development due to its simplicity, efficiency, and excellent support for concurrency. With the built-in net/http package, developers can create high-performance APIs and web applications using native Go code.

Let's take a look at a simple example of building a web application in Go without using any third-party web framework:

package main

import (
    "fmt"
    "log"
    "net/http"
)

func main() {
    http.HandleFunc("/", handler)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Hello, World!")
}

API Endpoint

In this example, we define a handler function that writes “Hello, World!” to the HTTP response. We then use the http.HandleFunc function to register the handler function for the root URL. Finally, we start the HTTP server by calling http.ListenAndServe(":8080", nil).

The net/http package also provides excellent support for routing and middleware. Let's take a look at an example that uses a middleware to log incoming requests:

package main

import (
    "fmt"
    "log"
    "net/http"
)

func main() {
    http.HandleFunc("/", handler)
    log.Fatal(http.ListenAndServe(":8080", logRequest(http.DefaultServeMux)))
}

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Hello, World!")
}

func logRequest(handler http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        log.Printf("%s %s %s\n", r.RemoteAddr, r.Method, r.URL.Path)
        handler.ServeHTTP(w, r)
    })
}

In this example, we define a logRequest middleware that logs incoming requests before passing them on to the handler function. We then pass the middleware to the http.ListenAndServe function, which applies the middleware to all incoming requests.

Conclusion

In conclusion, with the built-in net/http package, Go provides a powerful and flexible framework for building high-performance APIs and web applications. The language's excellent support for concurrency and its native code simplicity make it a popular choice for building scalable web applications.

Default image
@freecoder

With 15+ years in low-level development, I'm passionate about crafting clean, maintainable code.
I believe in readable coding, rigorous testing, and concise solutions.

Articles: 22