Skip to content

Commit

Permalink
path template casing example (#546)
Browse files Browse the repository at this point in the history
  • Loading branch information
haitch committed May 21, 2024
1 parent 59b17dc commit 26f2628
Show file tree
Hide file tree
Showing 5 changed files with 47 additions and 1 deletion.
5 changes: 4 additions & 1 deletion examples/hello/restful-hello-world.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,10 @@ func main() {
ws := new(restful.WebService)
ws.Route(ws.GET("/hello").To(hello))
restful.Add(ws)
log.Fatal(http.ListenAndServe(":8080", nil))

// DO NOT wrap http.ListenAndServe with log.Fatal in production
// or you won't be able to drain in-flight request gracefully, even you handle sigterm
log.Fatal(http.ListenAndServe(":8080", nil))
}

func hello(req *restful.Request, resp *restful.Response) {
Expand Down
33 changes: 33 additions & 0 deletions examples/path-case-sensitive/case-sensitive.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package main

import (
"io"
"log"
"net/http"

restful "github.com/emicklei/go-restful/v3"
)

// This example shows how to handle different casing of path template.
//
// GET http://localhost:8080/hola/Juan
// GET http://localhost:8080/HOLA/Juan
// GET http://localhost:8080/Hola/Juan

func main() {
ws := new(restful.WebService)

// hola is path template, to accept different casing of hola, we use regex matching with syntax {name:regex}
// - {: is nesserary to trigger the regex matching.
// - (?i) is to make the regex case-insensitive.
// it seems solve the issue, but there is a issue you might hit: https://github.com/emicklei/go-restful/issues/545
// to avoid partial matching, another regex pattern
// - ^$ is needed to match the whole route token.
ws.Route(ws.GET("/{:(?i)^hola$}/{name:*}").To(hola))
restful.Add(ws)
log.Fatal(http.ListenAndServe(":8080", nil))
}

func hola(req *restful.Request, resp *restful.Response) {
io.WriteString(resp, "hola "+req.PathParameter("name"))
}
5 changes: 5 additions & 0 deletions examples/path-case-sensitive/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module github.com/emicklei/go-restful/examples/pathtemplatecasing

go 1.14

require github.com/emicklei/go-restful/v3 v3.12.0
2 changes: 2 additions & 0 deletions examples/path-case-sensitive/go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
github.com/emicklei/go-restful/v3 v3.12.0 h1:y2DdzBAURM29NFF94q6RaY4vjIH1rtwDapwQtU84iWk=
github.com/emicklei/go-restful/v3 v3.12.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc=
3 changes: 3 additions & 0 deletions examples/path-case-sensitive/test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
GET http://localhost:8080/hola/Juan
GET http://localhost:8080/HOLA/Juan
GET http://localhost:8080/Hola/Juan

0 comments on commit 26f2628

Please sign in to comment.