Created
May 17, 2018 20:12
-
-
Save ericfialkowski/2ba2e3f40bec44e80f467fbcf731f4f3 to your computer and use it in GitHub Desktop.
Basic http server in go using gorilla mux
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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