Created
November 6, 2020 17:01
-
-
Save intrip/e1b9fab37d9a7cb47413467cec2e2fdd to your computer and use it in GitHub Desktop.
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 ( | |
"encoding/json" | |
"fmt" | |
"net/http" | |
"regexp" | |
"strconv" | |
) | |
// User is the exposed resource | |
type User struct { | |
ID uint `json:"id"` | |
Name string `json:"name"` | |
Email string `json:"email"` | |
} | |
// APIError message | |
type APIError struct { | |
message string | |
} | |
var users = []User{ | |
User{1, "Jacopo", "[email protected]"}, | |
} | |
type routeHandler struct{} | |
var rUsersIndex = regexp.MustCompile(`^/users/?$`) | |
var rUsersGet = regexp.MustCompile(`^/users/(\d+)$`) | |
func (routeHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { | |
switch { | |
case rUsersIndex.MatchString(req.URL.Path): | |
usersIndex(w, req) | |
case rUsersGet.MatchString(req.URL.Path): | |
matches := rUsersGet.FindStringSubmatch(req.URL.Path) | |
id, _ := strconv.Atoi(matches[1]) | |
usersGet(uint(id), w, req) | |
default: | |
notFound(w, req) | |
} | |
} | |
func usersIndex(w http.ResponseWriter, req *http.Request) { | |
usersJSON, err := json.Marshal(users) | |
if err != nil { | |
errorMsg(err, w, req) | |
return | |
} | |
fmt.Fprintf(w, string(usersJSON)) | |
} | |
func usersGet(id uint, w http.ResponseWriter, req *http.Request) { | |
var user User | |
for _, u := range users { | |
if u.ID == uint(id) { | |
user = u | |
} | |
} | |
if user == (User{}) { | |
notFound(w, req) | |
return | |
} | |
userJSON, err := json.Marshal(user) | |
if err != nil { | |
errorMsg(err, w, req) | |
return | |
} | |
fmt.Fprintf(w, string(userJSON)) | |
} | |
func notFound(w http.ResponseWriter, req *http.Request) { | |
w.WriteHeader(http.StatusNotFound) | |
} | |
func errorMsg(errStr error, w http.ResponseWriter, req *http.Request) { | |
w.WriteHeader(http.StatusBadRequest) | |
errorJSON, _ := json.Marshal(APIError{errStr.Error()}) | |
fmt.Fprintf(w, string(errorJSON)) | |
} | |
var server *http.Server | |
func start() { | |
mux := http.NewServeMux() | |
mux.Handle("/", routeHandler{}) | |
server = &http.Server{Addr: ":8000", Handler: mux} | |
server.ListenAndServe() | |
} | |
func stop() { | |
server.Close() | |
} | |
func main() { | |
start() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment