Skip to content

Commit 5632411

Browse files
feat(http_server): add solution for exercise 31_http_server (#50)
1 parent a66baae commit 5632411

1 file changed

Lines changed: 47 additions & 0 deletions

File tree

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package http_server
2+
3+
import (
4+
"fmt"
5+
"log"
6+
"net/http"
7+
"strings"
8+
)
9+
10+
// helloHandler handles requests to paths beginning with /hello/.
11+
// It extracts the first path segment after /hello/ and responds
12+
// with "Hello, {name}!\n". If no name is provided, it returns
13+
// a 400 Bad Request response.
14+
func helloHandler(w http.ResponseWriter, r *http.Request) {
15+
name := strings.TrimPrefix(r.URL.Path, "/hello/")
16+
17+
// Only take the first segment if multiple are present (e.g., /hello/a/b → "a").
18+
if i := strings.IndexByte(name, '/'); i >= 0 {
19+
name = name[:i]
20+
}
21+
22+
// Handle the case where no name is given (e.g., /hello/).
23+
if name == "" {
24+
http.Error(w, "name required", http.StatusBadRequest)
25+
return
26+
}
27+
28+
// Respond with plain text greeting.
29+
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
30+
fmt.Fprintf(w, "Hello, %s!\n", name)
31+
}
32+
33+
// init registers the /hello/ route when the package is loaded.
34+
// This ensures the handler is available even when tests start
35+
// their own server without calling StartServer.
36+
func init() {
37+
http.HandleFunc("/hello/", helloHandler)
38+
}
39+
40+
// StartServer starts an HTTP server on port :8080 using the
41+
// default multiplexer. Any server error is logged instead of
42+
// being silently ignored.
43+
func StartServer() {
44+
if err := http.ListenAndServe(":8080", nil); err != nil {
45+
log.Printf("http server stopped: %v", err)
46+
}
47+
}

0 commit comments

Comments
 (0)