Creating Simple Server in Go - 02
Anurag Affection
Posted on May 16, 2024
- First check the Go version by running the command
go version
- Create a folder
mkdir <folder_name>
- Switch to created folder
cd <folder_name>
- Initialize the go project by running the given command. You will get
go.mod
file.
go mod init <folder_name>
- Create a
main.go
file, use terminal or bash
notepad main.go
touch main.go
- Let's write some basic code in
main.go
file.
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello From Go \n")
fmt.Fprintf(w, "You are on %s route", r.URL.Path)
}
func main() {
fmt.Println("Your Server is running on http://localhost:8000")
http.HandleFunc("/", handler)
http.ListenAndServe(":8000", nil)
}
/*
--- 1. fmt , for formattting
--- 2. net/http , for creating server
--- both are standard package from go
The fmt.Fprintf function expects at least two arguments:
1. an io.Writer (w)
2. a format specifier
3. optional arguments
*/
- Run the code by following command
go run main.go
- You will see this output in console
Your Server is running on http://localhost:8000
- Visit
http://localhost:8000
on browser & try to change path of URL. You will see
Hello From Go
You are on / route
This was our simple server using Go.
That's for today. Thank You.
💖 💪 🙅 🚩
Anurag Affection
Posted on May 16, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
webdev Understanding HTTP, Cookies, Email Protocols, and DNS: A Guide to Key Internet Technologies
November 30, 2024
undefined How to Run Two MongoDB Instances on the Same Server (Standalone and Replica Set)
November 30, 2024