https://github.com/vuchkov/golang-rest-api
Simple Go (Golang) REST API (JSON)
https://github.com/vuchkov/golang-rest-api
api go golang json rest-api restful
Last synced: about 2 months ago
JSON representation
Simple Go (Golang) REST API (JSON)
- Host: GitHub
- URL: https://github.com/vuchkov/golang-rest-api
- Owner: vuchkov
- Created: 2025-02-21T14:06:57.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2025-02-21T14:12:40.000Z (over 1 year ago)
- Last Synced: 2025-03-08T13:48:46.964Z (over 1 year ago)
- Topics: api, go, golang, json, rest-api, restful
- Language: Go
- Homepage:
- Size: 2.93 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Simple Go (Golang) REST API (JSON)
The task requires implementing a GET API endpoint in Go using the `gorilla/mux` router.
The endpoint `/users` should return user data from a mocked database and support filtering by the `name` query parameter.
## Installation & Usage
1. Setup a Go project:
```
go mod init myapi
go get github.com/gorilla/mux
```
2. Create `main.go`:
```
package main
import (
"encoding/json"
"net/http"
"github.com/gorilla/mux"
"github.com/codility/rest_api_go/database"
)
func getUsersHandler(w http.ResponseWriter, r *http.Request) {
users := database.GetUsers()
queryName := r.URL.Query().Get("name")
var filteredUsers []database.User
for _, user := range users {
if queryName == "" || user.Name == queryName {
filteredUsers = append(filteredUsers, user)
}
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(filteredUsers)
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/users", getUsersHandler).Methods("GET")
http.ListenAndServe(":8080", r)
}
```
3. Result:
- `GET /users` → Returns all users.
- `GET /users?name=John` → Returns only users with `name="John"`.
- If no user matches the filter, returns an empty array `[]`.