Created
December 29, 2019 17:34
-
-
Save montanaflynn/8a00e1cf551c95305606ef14e0d17e9e to your computer and use it in GitHub Desktop.
Example of using Golang Chi router with a shared redis dependency
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 ( | |
"log" | |
"net/http" | |
"github.com/go-chi/chi" | |
"github.com/go-redis/redis" | |
) | |
type API struct { | |
router chi.Router | |
redis *redis.Client | |
} | |
func NewAPI() (*API, error) { | |
redisClient := redis.NewClient(&redis.Options{ | |
Addr: "127.0.0.1:6379", | |
}) | |
err := redisClient.Ping().Err() | |
if err != nil { | |
return nil, err | |
} | |
router := chi.NewRouter() | |
api := &API{ | |
redis: redisClient, | |
router: router, | |
} | |
return api, nil | |
} | |
func (a *API) getName(w http.ResponseWriter, r *http.Request) { | |
name, err := a.redis.Get("NAME").Result() | |
if err != nil { | |
http.Error(w, http.StatusText(404), 404) | |
return | |
} | |
w.Write([]byte(name)) | |
return | |
} | |
func (a *API) setName(w http.ResponseWriter, r *http.Request) { | |
keys, ok := r.URL.Query()["name"] | |
if !ok || len(keys[0]) < 1 { | |
http.Error(w, "Url Param 'name' is missing", 400) | |
return | |
} | |
name := keys[0] | |
err := a.redis.Set("NAME", name, 0).Err() | |
if err != nil { | |
log.Println(err) | |
http.Error(w, http.StatusText(500), 500) | |
return | |
} | |
http.Error(w, http.StatusText(201), 201) | |
return | |
} | |
func main() { | |
api, err := NewAPI() | |
if err != nil { | |
log.Fatal(err) | |
} | |
api.router.Get("/", api.getName) | |
api.router.Post("/", api.setName) | |
http.ListenAndServe(":8080", api.router) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment