Created
August 2, 2018 07:42
-
-
Save royvandam/ff2446a3cd7e7c687e5249685c0d5a0d to your computer and use it in GitHub Desktop.
Roles API test
This file contains hidden or 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 ( | |
"net/http" | |
"github.com/gorilla/mux" | |
"log" | |
"encoding/json" | |
) | |
type Role struct { | |
RoleName string `json:"name"` | |
RoleType string `json:"type"` | |
} | |
type Roles []Role | |
var roles Roles = Roles{ | |
Role{RoleName: "roydam", RoleType: "employee"}, | |
Role{RoleName: "miccar", RoleType: "employee"}, | |
Role{RoleName: "corpdb-team", RoleType: "group"}, | |
} | |
func RolesApiHandler(w http.ResponseWriter, r *http.Request) { | |
w.Header().Set("Content-Type", "application/json; charset=UTF-8") | |
w.WriteHeader(http.StatusOK) | |
json.NewEncoder(w).Encode(roles) | |
} | |
func RoleApiHandler(w http.ResponseWriter, r *http.Request) { | |
params := mux.Vars(r) | |
w.Header().Set("Content-Type", "application/json; charset=UTF-8") | |
for _, role := range roles { | |
if role.RoleName == params["roleName"] { | |
w.WriteHeader(http.StatusOK) | |
json.NewEncoder(w).Encode(role) | |
return | |
} | |
} | |
w.WriteHeader(http.StatusNotFound) | |
} | |
func main() { | |
r := mux.NewRouter() | |
api := r.PathPrefix("/api").Subrouter() | |
api.Path("/roles").Methods("GET").HandlerFunc(RolesApiHandler); | |
api.Path("/role/{roleName}").Methods("GET").HandlerFunc(RoleApiHandler); | |
log.Fatal(http.ListenAndServe(":8080", r)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment