Skip to content

Commit

Permalink
Merge pull request #2 from edmarfelipe/feat/code_coverage
Browse files Browse the repository at this point in the history
feat: add new router
  • Loading branch information
edmarfelipe authored Aug 24, 2024
2 parents 8bd3fc6 + 8bab902 commit 20026cf
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 1 deletion.
4 changes: 3 additions & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -64,5 +64,7 @@ jobs:
if: github.event_name == 'pull_request'
runs-on: ubuntu-latest
needs: test
permissions:
actions: read # to download
steps:
- uses: fgrosse/go-coverage-report@v1.0.2
- uses: fgrosse/go-coverage-report@v1.0.2
29 changes: 29 additions & 0 deletions internal/httpserver/handler_hello.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package httpserver

import "net/http"

var (
msgs = map[string]string{
"en": "Hello",
"es": "Hola",
"pt": "Olá",
}
)

type HelloResponse struct {
Message string `json:"message"`
}

func HelloHandler(w http.ResponseWriter, r *http.Request) {
lang := r.URL.Query().Get("lang")
if lang == "" {
lang = "en"
}

if _, ok := msgs[lang]; !ok {
WriteJSON(w, http.StatusBadRequest, ErrorResponse{Error: "invalid language"})
return
}

WriteJSON(w, http.StatusOK, HelloResponse{Message: msgs[lang]})
}
33 changes: 33 additions & 0 deletions internal/httpserver/handler_hello_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package httpserver_test

import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"

"github.com/edmarfelipe/go-ci/internal/httpserver"
)

func TestHelloHandler(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(httpserver.HelloHandler))

t.Run("Should return a hello response with default language", func(t *testing.T) {
resp, err := http.Get(srv.URL)
if err != nil {
t.Fatalf("expected no error, got %v", err)
}

if resp.StatusCode != http.StatusOK {
t.Fatalf("expected status code %d, got %d", http.StatusOK, resp.StatusCode)
}
defer resp.Body.Close()

var hello httpserver.HelloResponse
json.NewDecoder(resp.Body).Decode(&hello)

if hello.Message != "Hello" {
t.Fatalf("expected message %s, got %s", "Hello", hello.Message)
}
})
}
1 change: 1 addition & 0 deletions internal/httpserver/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ type HTTPServer struct {
func New(cfg *env.Env) *HTTPServer {
router := http.NewServeMux()
router.HandleFunc("GET /health", HealthHandler)
router.HandleFunc("GET /hello", HelloHandler)

return &HTTPServer{
srv: &http.Server{
Expand Down

0 comments on commit 20026cf

Please sign in to comment.