Standard Library

In Go we have the possibility to create REST APIs using:

  • Standard Library net/http;
  • Frameworks restFull.

Go has created a complete native lib so that we can enjoy its power in creating REST apis. 🇧🇷

When we build REST APIs using Standard Library Go we are simply natively implementing our api using pkg. net/http😍.

standard_library example:


.....
mux := http.NewServeMux()

mux.HandleFunc("/v1/api/ping", Ping)

mux.Handle("/v2/api/ping", http.HandlerFunc(Ping2))

log.Fatal(http.ListenAndServe(":8080",nil))
.....
                        

Standard Library Go is very powerful, it's so powerful that most rESTFull Frameworks are developed using net/http.

standard_library.go

.....
func main() {
    log.Printf("\nServer run 8080\n")
    err := http.ListenAndServe(":8080",
        http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            w.Write([]byte("DevopsBH for Golang simple" + r.URL.Path))
        }))
    log.Fatal(err)
}
....
                        

.....
tr := &http.Transport{
	MaxIdleConns:       10,
	IdleConnTimeout:    30 * time.Second,
	DisableCompression: true,
}
client := &http.Client{Transport: tr}
resp, err := client.Get("https://example.com")
....
                        

.....
s := &http.Server{
	Addr:           ":8080",
	Handler:        myHandler,
	ReadTimeout:    10 * time.Second,
	WriteTimeout:   10 * time.Second,
	MaxHeaderBytes: 1 << 20,
}
log.Fatal(s.ListenAndServe())
....