Skip to content

Instantly share code, notes, and snippets.

@judwhite
Last active January 13, 2021 07:43
Show Gist options
  • Save judwhite/22f06262e7d0ceaf17ddcda30bf78374 to your computer and use it in GitHub Desktop.
Save judwhite/22f06262e7d0ceaf17ddcda30bf78374 to your computer and use it in GitHub Desktop.
Gorilla Mux Example v1
package main
import (
"encoding/json"
"log"
"net/http"
"github.com/gorilla/mux"
)
func main() {
r := router()
log.Fatal(http.ListenAndServe(":8080", r))
}
func router() *mux.Router {
r := mux.NewRouter()
api := r.PathPrefix("/api").Subrouter()
api.HandleFunc("/version", handleGetVersion)
return r
}
func handleGetVersion(w http.ResponseWriter, r *http.Request) {
type getVersionResponse struct {
Message string `json:"msg"`
}
response := getVersionResponse{Message: "Hello!"}
JSON(w, response)
}
func JSON(w http.ResponseWriter, data interface{}) {
enc := json.NewEncoder(w)
err := enc.Encode(data)
if err != nil {
log.Println(err.Error())
w.WriteHeader(http.StatusInternalServerError)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment