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 http://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 http://localhost:8080/hello. If the server responds with "Hello!"
visit our next post of the series lightweight-docker-images-why-and-how?
Read More Blogs
Encoding and Decoding
Thu Dec 01 2022
Encoding and decoding are used in many forms of communications, including computing, data communications, programming, digital electronics and human communications. These two processes involve changing the format of content for optimal transmission or storage.
Caching In GoLang Using Redis
Wed Nov 09 2022
Most applications depend on data, whether it comes from a database or an API sends a network request to the API server and returns the data as the response, These round trips take time and can increase your application response time to users. Furthermore, most APIs limit the number of requests they can serve an application within a specific time frame a process known as rate limiting.
Deploying AWS Lambda in GoLang with Serverless framework
Wed Dec 07 2022
AWS Lambda is a serverless computing service provided by Amazon Web Services (AWS) AWS Lambda lets you run code without provisioning or managing servers.
Let’s Start a Conversation!