DEV Community

Anurag Affection
Anurag Affection

Posted on • Edited on

Creating Simple Server in Go - 02

#go
  • First check the Go version by running the command
go version
Enter fullscreen mode Exit fullscreen mode
  • Create a folder
mkdir <folder_name>
Enter fullscreen mode Exit fullscreen mode
  • Switch to created folder
cd <folder_name>
Enter fullscreen mode Exit fullscreen mode
  • Initialize the go project by running the given command. You will get go.mod file.
go mod init <folder_name>
Enter fullscreen mode Exit fullscreen mode
  • Create a main.go file, use terminal or bash
notepad main.go 
touch main.go
Enter fullscreen mode Exit fullscreen mode
  • 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

*/
Enter fullscreen mode Exit fullscreen mode
  • Run the code by following command
go run main.go 
Enter fullscreen mode Exit fullscreen mode
  • You will see this output in console
Your Server is running on http://localhost:8000
Enter fullscreen mode Exit fullscreen mode
  • Visit http://localhost:8000on browser & try to change path of URL. You will see
Hello From Go 
You are on / route
Enter fullscreen mode Exit fullscreen mode

This was our simple server using Go.
That's for today. Thank You.

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more