Skip to content

Instantly share code, notes, and snippets.

@ericfialkowski
Created May 17, 2018 20:12
Show Gist options
  • Save ericfialkowski/2ba2e3f40bec44e80f467fbcf731f4f3 to your computer and use it in GitHub Desktop.
Save ericfialkowski/2ba2e3f40bec44e80f467fbcf731f4f3 to your computer and use it in GitHub Desktop.
Basic http server in go using gorilla mux
package main
import (
"flag"
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
)
var port= flag.Int("port", 8000, "Port to bind to")
var ip= flag.String("ip", "", "IP Address to bind to, blank for all")
func init() {
flag.Parse()
}
func main() {
router := mux.NewRouter()
router.HandleFunc("/", helloWorldHandler).Methods(http.MethodGet)
bindAddr := fmt.Sprintf("%s:%d", *ip, *port)
fmt.Printf("Listening to %s\n", bindAddr)
log.Fatal(http.ListenAndServe(bindAddr, router))
}
func helloWorldHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Header().Add("Content-Type", "text/plain")
fmt.Fprintln(w, "Hello World")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment