Skip to content

Instantly share code, notes, and snippets.

@dradtke
Created February 4, 2016 16:48
Show Gist options
  • Select an option

  • Save dradtke/c4c4e31bfc995dda671a to your computer and use it in GitHub Desktop.

Select an option

Save dradtke/c4c4e31bfc995dda671a to your computer and use it in GitHub Desktop.
Go's "hello world" of web applications.
package main
import (
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
)
// Constant specifying which port the app should listen on.
const PORT = 8080
// Index is an HTTP handler. It's given a ResponseWriter, which is what
// handlers write to in order to respond to the client, and a pointer to
// a Request struct, which contains information about the request.
func Index(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello world"))
}
func main() {
// Create the router and set up some endpoints.
router := mux.NewRouter()
router.HandleFunc("/", Index)
// Listen for and serve incoming requests. Requests are served in
// their own goroutine, aka a lightweight thread.
log.Printf("-- application is listening on port %d --", PORT)
if err := http.ListenAndServe(fmt.Sprintf(":%d", PORT), router); err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment