In this article, we will cover some of the basics of building web applications in Go, including routing, handling requests, and serving static files.
Routing in Go is typically handled using the “net/http” package, which provides functions for registering routes and handling HTTP requests. Here is a simple example of a basic web server in Go:
“`go
package main
import (
“fmt”
“net/http”
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, “Hello, World!”)
}
func main() {
http.HandleFunc(“/”, handler)
http.ListenAndServe(“:8080”, nil)
}
“`
In this example, we define a handler function that takes an http.ResponseWriter and an http.Request as arguments. The handler function simply writes “Hello, World!” to the response writer. We then register our handler function for the root route (“/”) using http.HandleFunc and start the server using http.ListenAndServe.
Go also provides a built-in file server for serving static files, such as HTML, CSS, and JavaScript files. Here is an example of serving static files in Go:
“`go
package main
import (
“net/http”
)
func main() {
http.Handle(“/”, http.FileServer(http.Dir(“./static”)))
http.ListenAndServe(“:8080”, nil)
}
“`
In this example, we use http.FileServer to create a file server that serves files from the “static” directory. We then register the file server for the root route (“/”) using http.Handle and start the server using http.ListenAndServe.
These examples provide a basic overview of web development in Go. There are many additional features and libraries available for building web applications in Go, such as Gorilla Mux for more advanced routing, Gorm for database interaction, and Go templates for rendering HTML. I encourage you to explore these features further and continue learning about web development in Go.
No responses yet