Last active
January 13, 2021 07:43
-
-
Save judwhite/22f06262e7d0ceaf17ddcda30bf78374 to your computer and use it in GitHub Desktop.
Gorilla Mux Example v1
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 ( | |
"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