Skip to content

Instantly share code, notes, and snippets.

@gufranmirza
Created July 7, 2018 19:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gufranmirza/2861f10e8bad3e3a8491f9fc9f52753a to your computer and use it in GitHub Desktop.
Save gufranmirza/2861f10e8bad3e3a8491f9fc9f52753a to your computer and use it in GitHub Desktop.
// This is the name of our package
// Everything with this package name can see everything
// else inside the same package, regardless of the file they are in
package main
// These are the libraries we are going to use
// Both "fmt" and "net" are part of the Go standard library
import (
// "fmt" has methods for formatted I/O operations (like printing to the console)
"fmt"
// The "net/http" library has methods to implement HTTP clients and servers
"net/http"
)
func main() {
// The "HandleFunc" method accepts a path and a function as arguments
// (Yes, we can pass functions as arguments, and even trat them like variables in Go)
// However, the handler function has to have the appropriate signature (as described by the "handler" function below)
http.HandleFunc("/", handler)
// After defining our server, we finally "listen and serve" on port 8080
// The second argument is the handler, which we will come to later on, but for now it is left as nil,
// and the handler defined above (in "HandleFunc") is used
http.ListenAndServe(":8080", nil)
}
// "handler" is our handler function. It has to follow the function signature of a ResponseWriter and Request type
// as the arguments.
func handler(w http.ResponseWriter, r *http.Request) {
// For this case, we will always pipe "Hello World" into the response writer
fmt.Fprintf(w, "Hello World!")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment