### Example: using package-level default container Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/container.md Example showing how to install a global filter, register a WebService, and serve on the default container via http.DefaultServeMux. ```go restful.Filter(globalLogging) // install a global filter restful.Add(NewUserService()) // register a WebService log.Fatal(http.ListenAndServe(":8080", nil)) // DefaultContainer is served via http.DefaultServeMux ``` -------------------------------- ### Example using Returns, ReturnsWithHeaders, DefaultReturns Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/routebuilder.md Demonstrates documenting multiple response codes, response headers, and a default response for a GET route. ```go ws.Route(ws.GET("/{user-id}").To(u.findUser). Writes(User{}). Returns(200, "OK", User{}). Returns(404, "Not Found", nil). Returns(500, "Server Error", restful.ServiceError{}). ReturnsWithHeaders(200, "OK", User{}, map[string]restful.Header{ "X-Rate-Limit": {Items: &restful.Items{Type: "integer"}, Description: "requests remaining"}, }). DefaultReturns("unexpected error", restful.ServiceError{})) ``` -------------------------------- ### Example: using Container.Add Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/container.md Example showing how to create a new container and add a WebService to it. ```go container := restful.NewContainer() container.Add(usersResource.WebService()) ``` -------------------------------- ### Example: Adding and removing routes with dynamic routes enabled Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/webservice.md Example showing how to enable dynamic routes and add/remove a route at runtime. The example creates a WebService, enables dynamic routes, adds a GET route, and then removes it. ```go ws := new(restful.WebService).Path("/events") ws.SetDynamicRoutes(true) // allow adding/removing routes at runtime ws.Route(ws.GET("/{id}").To(findEvent)) if err := ws.RemoveRoute("/events/{id}", "GET"); err != nil { log.Print(err) } ``` -------------------------------- ### Dispatch method example Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/container.md Example of using Container.Dispatch as an http.Handler function in a standalone setup. ```go // Standalone use: use the container as an http.Handler function http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { container.Dispatch(w, r) }) ``` -------------------------------- ### RegisteredWebServices method example Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/container.md Example of iterating over the registered web services and printing each root path. ```go for _, ws := range container.RegisteredWebServices() { fmt.Println(ws.RootPath()) } ``` -------------------------------- ### Example: Setting Consumes and Produces on a WebService Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/webservice.md Example showing how to set the Consumes and Produces content types on a WebService. The example configures the WebService to accept and return XML and JSON. ```go ws := new(restful.WebService) ws.Path("/users"). Consumes(restful.MIME_XML, restful.MIME_JSON). Produces(restful.MIME_JSON, restful.MIME_XML) ``` -------------------------------- ### Using HTTP verb shortcuts to define routes Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/webservice.md Example of using GET, POST, and the generic Method shortcut to define routes on a WebService. The Method shortcut allows arbitrary HTTP verbs. ```go ws.Route(ws.GET("/{user-id}").To(u.findUser)) ws.Route(ws.POST("").To(u.createUser)) ws.Route(ws.Method("TRACE").Path("/debug").To(u.traceHandler)) // arbitrary verb ``` -------------------------------- ### Example — adapter for a third-party logger Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/logging.md Adapts a slog.Logger to the StdLogger interface. The adapter's Print and Printf methods delegate to slog's Info method, and SetLogger installs it as the package logger. ```go type slogAdapter struct{ l *slog.Logger } func (a slogAdapter) Print(v ...interface{}) { a.l.Info(fmt.Sprint(v...)) } func (a slogAdapter) Printf(f string, v ...interface{}) { a.l.Info(fmt.Sprintf(f, v...)) } func init() { restfullog.SetLogger(slogAdapter{l: slog.Default()}) } ``` -------------------------------- ### Router method example Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/container.md Example of setting a slower JSR311-aligned router using restful.RouterJSR311{}. ```go container.Router(restful.RouterJSR311{}) // slower JSR311-aligned router ``` -------------------------------- ### WebService usage example Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/webservice.md Creates a WebService, sets its path, API version, and documentation, then prints the root path and version. ```go ws := new(restful.WebService) ws.Path("/users").ApiVersion("v1").Doc("User management service") fmt.Println(ws.RootPath()) // "/users" fmt.Println(ws.Version()) // "v1" ``` -------------------------------- ### Do method usage example Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/routebuilder.md Example showing how to use Do with a custom Returns500 function to add a 500 response to a DELETE route. ```go func Returns500(b *restful.RouteBuilder) { b.Returns(500, "Internal Server Error", restful.ServiceError{}) } ws.Route(ws.DELETE("/{name}").To(t.deletePerson).Do(Returns500)) ``` -------------------------------- ### Example: configuring recovery and error handling Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/container.md Shows how to configure a Container to catch panics, set custom recover and service error handlers, and enable content encoding. The example sets DoNotRecover(false) to catch panics, replaces the recover handler to write a 500 response, replaces the service error handler to write the error code and message, and enables gzip/deflate compression. ```go container := restful.NewContainer() container.DoNotRecover(false) // catch panics → HTTP 500 container.RecoverHandler(func(reason interface{}, w http.ResponseWriter) { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(w, "panic: %v", reason) }) container.ServiceErrorHandler(func(err restful.ServiceError, req *restful.Request, resp *restful.Response) { resp.WriteHeader(err.Code) resp.Write([]byte(err.Message)) }) container.EnableContentEncoding(true) // gzip/deflate responses ``` -------------------------------- ### ServeHTTP usage example Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/container.md Shows how to use a Container as the Handler for an http.Server, leveraging ServeHTTP internally. ```go server := &http.Server{Addr: ":8081", Handler: container} // ServeHTTP used internally log.Fatal(server.ListenAndServe()) ``` -------------------------------- ### Recommended preloaded cache example Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/entities-and-encoding.md Sets the compressor provider to a bounded cache with 20 writers and 20 readers. This is the recommended way to preload the cache. ```go restful.SetCompressorProvider(restful.NewBoundedCachedCompressors(20, 20)) ``` -------------------------------- ### CORS filter usage example Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/filters.md Shows how to instantiate CrossOriginResourceSharing with common configuration and register it as a filter. The example sets allowed headers, domains, methods, and disables cookies. ```go cors := restful.CrossOriginResourceSharing{ ExposeHeaders: []string{"X-My-Header"}, AllowedHeaders: []string{"Content-Type", "Accept", "Authorization"}, AllowedDomains: []string{"example.com", ".*"}, // ".*" allows all AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}, CookiesAllowed: false, MaxAge: 3600, Container: restful.DefaultContainer, // used to compute allowed methods } restful.Filter(cors.Filter) ``` -------------------------------- ### Example — plug in a custom logger Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/logging.md Shows how to replace the default logger with a custom stdlib logger writing to stdout with a custom prefix. Call in init() to apply before any logging occurs. ```go import ( stdlog "log" "os" restfullog "github.com/emicklei/go-restful/v3/log" ) func init() { restfullog.SetLogger(stdlog.New(os.Stdout, "[my-service/restful] ", stdlog.LstdFlags)) } ``` -------------------------------- ### RouteBuilder usage example Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/routebuilder.md Configures a GET route with a filter, a condition on the X-API-Version header, allowed methods without content type, and content encoding enabled. The condition returns false if the header is not "2", preventing route selection. ```go ws.Route(ws.GET("/{user-id}"). Filter(routeLogging).Filter(NewCountFilter().routeCounter). If(func(r *http.Request) bool { return r.Header.Get("X-API-Version") == "2" }). AllowedMethodsWithoutContentType([]string{"GET"}). ContentEncodingEnabled(true). To(u.findUser)) ``` -------------------------------- ### Handle and HandleWithFilter usage example Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/container.md Registers a metrics handler and an admin handler with filters applied. ```go container := restful.NewContainer() container.Handle("/metrics", promhttp.Handler()) container.HandleWithFilter("/admin", adminHandler) // container filters apply ``` -------------------------------- ### Container usage example Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/container.md Shows how to create a Container and serve it with an http.Server. The container is used as the handler, and the server listens on port 8081. ```go container := restful.NewContainer() server := &http.Server{Addr: ":8081", Handler: container} log.Fatal(server.ListenAndServe()) ``` -------------------------------- ### HeaderParameter usage example Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/request.md Example of calling HeaderParameter to retrieve the Authorization header value. ```go token := req.HeaderParameter("Authorization") ``` -------------------------------- ### Example: defining routes with CurlyRouter Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/routers.md Shows how to define routes with CurlyRouter (the default). Demonstrates a plain parameter, a Google custom method, a tail wildcard, and a regex parameter. ```go container := restful.NewContainer() // CurlyRouter is the default; no extra config ws := new(restful.WebService) ws.Path("/meetings") ws.Route(ws.GET("/{id}").To(getMeeting)) ws.Route(ws.GET("/archive:rewind").To(rewindArchive)) // Google custom method ws.Route(ws.GET("/static/{subpath:*}").To(serveStatic)) // tail wildcard ws.Route(ws.GET("/users/{name:[A-Z][a-z]+}").To(findUser)) // regex parameter ``` -------------------------------- ### Remove method example Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/container.md Example usage of Container.Remove. It creates a container, adds a WebService, and removes it, logging a fatal error if removal fails (which only happens when using http.DefaultServeMux). ```go container := restful.NewContainer() ws := NewUserService() container.Add(ws) if err := container.Remove(ws); err != nil { log.Fatal(err) // only fails when using http.DefaultServeMux } ``` -------------------------------- ### Example: using Data accessor Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/parameter.md Shows how to retrieve the ParameterData from a query parameter and print its fields. The Kind field is compared against restful.QueryParameterKind. ```go p := ws.QueryParameter("q", "search term") data := p.Data() fmt.Println(data.Name, data.Kind == restful.QueryParameterKind, data.DataType) ``` -------------------------------- ### PathParameter and PathParameters usage example Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/request.md Example of using PathParameter and PathParameters inside a handler. PathParameter returns the value for a named path parameter, and PathParameters returns the full map of path parameters. ```go func findUser(req *restful.Request, resp *restful.Response) { id := req.PathParameter("user-id") // GET /users/42 → "42" all := req.PathParameters() // map[string]string{"user-id": "42"} } ``` -------------------------------- ### Response Hijack example (WebSocket-style) Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/response.md Demonstrates using Hijack to obtain the underlying connection and read/writer. Only works if the underlying writer supports the Hijacker interface; otherwise Hijack returns an error. ```go // only works if the underlying writer supports Hijacker if conn, rw, err := resp.Hijack(); err == nil { _ = conn _ = rw } ``` -------------------------------- ### Example: Registering OPTIONSFilter Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/container.md Registers the OPTIONSFilter on the DefaultContainer to automatically answer OPTIONS requests. ```go restful.Filter(restful.OPTIONSFilter()) // automatic OPTIONS answers on DefaultContainer ``` -------------------------------- ### Filter method example Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/container.md Example of using the Filter method to add a global logging filter. The filter logs the HTTP method and URL, then must call chain.ProcessFilter to pass control on. ```go container := restful.NewContainer() container.Filter(func(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { log.Printf("[global] %s %s", req.Request.Method, req.Request.URL) chain.ProcessFilter(req, resp) // must pass control on }) ``` -------------------------------- ### Manual per-response compression with NewCompressingResponseWriter Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/entities-and-encoding.md Shows how to install a per-response compressor manually using NewCompressingResponseWriter with ENCODING_GZIP. Handles errors by writing an internal server error and defers closing the writer. ```go // install a per-response compressor manually w, err := restful.NewCompressingResponseWriter(rw, restful.ENCODING_GZIP) if err != nil { rw.WriteHeader(http.StatusInternalServerError) return } defer w.Close() io.WriteString(w, "compressed payload") ``` -------------------------------- ### NewResponse example Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/response.md Creates a new Response using an existing http.ResponseWriter. The writer must be provided and is used for all subsequent writes. ```go resp := restful.NewResponse(writer) ``` -------------------------------- ### Header/serialization control usage example Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/response.md Demonstrates chaining PrettyPrint and AddHeader on a Response. PrettyPrint(false) produces compact JSON, and AddHeader returns the receiver for chaining. ```go resp.PrettyPrint(false) // compact JSON resp.AddHeader("X-Powered-By", "go-restful") // chainable ``` -------------------------------- ### QueryParameter and QueryParameters usage example Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/request.md Example of using QueryParameter and QueryParameters to read query string values. QueryParameter returns the first value for a name, while QueryParameters returns all values for that name. ```go q := req.QueryParameter("q") // GET /search?q=terms → "terms" tags := req.QueryParameters("tag") // GET /search?tag=a&tag=b → ["a" "b"] ``` -------------------------------- ### Iterating routes to disable compression Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/routebuilder.md Example loop over ws.Routes() to find a route object by path and disable compression for it. ```go for _, rt := range ws.Routes() { // find the route object by path and disable compression for it } ``` -------------------------------- ### Param usage example Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/webservice.md Documents a root path variable by appending a PathParameter to the WebService. Use this to declare a parameter that applies to the service's root path. ```go ws.Param(ws.PathParameter("tenant-id", "tenant scope")) // documents root path variable ``` -------------------------------- ### NewRequest usage example Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/request.md Wraps an existing *http.Request into a restful.Request for use with go-restful helpers. ```go wrapped := restful.NewRequest(httpReq) ``` -------------------------------- ### Define a WebService route with path parameter Source: https://github.com/emicklei/go-restful/blob/v3/README.md Shows how to define a WebService with a route that maps a GET request to a handler function, including path parameters and documentation. ```go ws := new(restful.WebService) ws. Path("/users"). Consumes(restful.MIME_XML, restful.MIME_JSON). Produces(restful.MIME_JSON, restful.MIME_XML) ws.Route(ws.GET("/{user-id}").To(u.findUser). Doc("get a user"). Param(ws.PathParameter("user-id", "identifier of the user").DataType("string")). Writes(User{})) ... func (u UserResource) findUser(request *restful.Request, response *restful.Response) { id := request.PathParameter("user-id") ... } ``` -------------------------------- ### Example: configuring RouterJSR311 on a container Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/routers.md Shows how to set RouterJSR311 as the router for a container. This alternative is slower but aligns with the JSR311 specification. ```go container := restful.NewContainer() container.Router(restful.RouterJSR311{}) // slower, spec-aligned alternative ``` -------------------------------- ### Example using Reads, Param, Writes Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/routebuilder.md Shows how to declare a path parameter and request body type with Reads, and response payload types with Writes. Reads automatically adds a body parameter with DataType set to the type name. ```go ws.Route(ws.PUT("/{user-id}").To(u.upsertUser). Param(ws.PathParameter("user-id", "identifier of the user").DataType("string")). Reads(User{})) // body parameter added automatically, DataType "main.User" ws.Route(ws.GET("/users").To(u.findAll). Writes([]User{}). Returns(200, "OK", []User{})) ``` -------------------------------- ### Using RouteReader with SelectedRoute Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/routebuilder.md Shows how to retrieve the RouteReader from a request and print its method, path, and operation. The example checks for nil before accessing. ```go if rr := req.SelectedRoute(); rr != nil { fmt.Println(rr.Method(), rr.Path(), rr.Operation()) } ``` -------------------------------- ### Response status/content tracking example Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/response.md Shows how to use WriteHeader, StatusCode, Write, and ContentLength together. After writing a 202 status and body, StatusCode returns 202 and ContentLength returns the number of bytes written through resp. ```go resp.WriteHeader(http.StatusAccepted) fmt.Println(resp.StatusCode()) // 202 n, _ := resp.Write([]byte("ok")) fmt.Println(resp.ContentLength()) // n (assumes all writes go through resp) ``` -------------------------------- ### Example — enable diagnostic tracing Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/logging.md Enables detailed trace logging for the whole package by setting a trace logger. Tracing can be turned off later with EnableTracing(false) without changing the logger. ```go restful.TraceLogger(log.New(os.Stdout, "[restful] ", log.LstdFlags|log.Lshortfile)) // tracing now enabled for the whole package // later, to switch it off without changing the logger: restful.EnableTracing(false) ``` -------------------------------- ### Chaining filters on WebService Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/webservice.md Example of chaining two filters on a WebService instance. The filters are applied in order to all routes of the service. ```go ws.Filter(webserviceLogging).Filter(measureTime) // chained ws-level filters ``` -------------------------------- ### OPTIONSFilter usage example Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/filters.md Shows how to register the OPTIONSFilter on the default container and on a custom container. Use the default container for simple cases, or the custom container when you have a custom container instance. ```go // on the default container: restful.Filter(restful.OPTIONSFilter()) // or on a custom container: container.Filter(container.OPTIONSFilter) ``` -------------------------------- ### Example: Using parameter factories in route and package-level context Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/webservice.md Shows two usage patterns: chaining mutators on a PathParameter within a route definition, and using the package-level QueryParameter function without a WebService instance. The first sets DataType and DefaultValue; the second sets PossibleValues. ```go ws.Route(ws.GET("/{user-id}").To(u.findUser). Param(ws.PathParameter("user-id", "identifier of the user").DataType("integer").DefaultValue("1"))) // package-level alternative used without a WebService instance: p := restful.QueryParameter("q", "search term").PossibleValues([]string{"a", "b"}) ``` -------------------------------- ### Example: fully documented path parameter and query parameter with enum Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/parameter.md Shows chaining mutators on a path parameter and a query parameter. The path parameter uses DataType, DataFormat, DefaultValue, Minimum, Maximum, and Required. The query parameter uses PossibleValues, CollectionFormat, and AllowMultiple. ```go ws.Route(ws.GET("/{user-id}").To(u.findUser). Param(ws.PathParameter("user-id", "identifier of the user"). DataType("integer"). DataFormat("int64"). DefaultValue("1"). Minimum(1). Maximum(1_000_000). Required(true))) // query param with enum + collection format ws.Route(ws.GET("/search").To(u.search). Param(ws.QueryParameter("status", "filter"). PossibleValues([]string{"open", "closed"}). CollectionFormat(restful.CollectionFormatCSV). AllowMultiple(true))) ``` -------------------------------- ### Swap JSON decoder for custom float handling Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/entities-and-encoding.md Example of replacing the JSON decoder to use json.Number, useful for custom float handling. ```go // swap the JSON encoder/decoder functions (e.g. for custom float handling) restful.NewDecoder = func(r io.Reader) *json.Decoder { dec := json.NewDecoder(r) dec.UseNumber() return dec } ``` -------------------------------- ### Method and HTTP-verb shortcuts Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/webservice.md Creates RouteBuilder instances for registering routes with specific HTTP methods. The Method method accepts an arbitrary HTTP method, while the verb shortcuts (HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS) are convenience wrappers. ```APIDOC ## Method and HTTP-verb shortcuts ### Description Creates a RouteBuilder with the given HTTP method, inheriting the service path and the TypeNameHandleFunction. The verb shortcuts are equivalent to calling .Method("").Path(subPath). ### Method Method, HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS ### Endpoint func (w *WebService) Method(httpMethod string) *RouteBuilder func (w *WebService) HEAD(subPath string) *RouteBuilder func (w *WebService) GET(subPath string) *RouteBuilder func (w *WebService) POST(subPath string) *RouteBuilder func (w *WebService) PUT(subPath string) *RouteBuilder func (w *WebService) PATCH(subPath string) *RouteBuilder func (w *WebService) DELETE(subPath string) *RouteBuilder func (w *WebService) OPTIONS(subPath string) *RouteBuilder ### Parameters #### Path Parameters - **httpMethod** (string) - Required - The HTTP method (uppercase) for the route. - **subPath** (string) - Required - The sub-path for the route, relative to the service root path. ### Request Example ```go ws.Route(ws.GET("/{user-id}").To(u.findUser)) ws.Route(ws.POST("").To(u.createUser)) ws.Route(ws.Method("TRACE").Path("/debug").To(u.traceHandler)) // arbitrary verb ``` ### Response #### Success Response - **\*RouteBuilder** - A RouteBuilder pre-seeded with the service root path and type name handler. ``` -------------------------------- ### Adapt gorilla/handlers-style middleware with HttpMiddlewareHandlerToFilter Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/filters.md Converts a standard HTTP middleware into a FilterFunction using HttpMiddlewareHandlerToFilter. The example logs the request path and calls next.ServeHTTP to continue the chain. ```go // adapt github.com/gorilla/handlers.CompressHandler-style middleware restful.Filter(restful.HttpMiddlewareHandlerToFilter(func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { log.Printf("middleware: %s", r.URL.Path) next.ServeHTTP(w, r) }) })) ``` -------------------------------- ### JSON/XML convenience writer usage example Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/response.md Shows typical calls to the convenience writers: WriteAsJson for a 200 JSON response, WriteHeaderAndJson for a custom status and content type, and WriteHeaderAndXml for a custom status XML response. ```go resp.WriteAsJson(user) resp.WriteHeaderAndJson(201, user, "application/json; charset=utf-8") resp.WriteHeaderAndXml(200, user) ``` -------------------------------- ### CurrentCompressorProvider and SetCompressorProvider functions Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/entities-and-encoding.md Functions to get and set the active compressor provider. SetCompressorProvider panics with "cannot set compressor provider to nil" if passed nil. Used by Request.ReadEntity and CompressingResponseWriter.Close. ```go // compressors.go:44 func CurrentCompressorProvider() CompressorProvider // compressors.go:49 func SetCompressorProvider(p CompressorProvider) ``` -------------------------------- ### Using SetAttribute and Attribute in a filter and handler Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/request.md Shows how to store a start time in a filter and retrieve it in the handler using a type assertion. The handler checks the ok flag before computing elapsed time. ```go // in a filter: req.SetAttribute("startTime", time.Now()) // in the handler: if start, ok := req.Attribute("startTime").(time.Time); ok { elapsed := time.Since(start) } ``` -------------------------------- ### HTTP verb shortcut method signatures Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/webservice.md Signatures for the Method and HTTP-verb shortcut methods (HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS) on WebService. All return a *RouteBuilder pre-seeded with the service root path and type name handler. ```go // web_service.go:208 func (w *WebService) Method(httpMethod string) *RouteBuilder // web_service.go:273 (and identical for GET, POST, PUT, PATCH, DELETE, OPTIONS) func (w *WebService) HEAD(subPath string) *RouteBuilder func (w *WebService) GET(subPath string) *RouteBuilder func (w *WebService) POST(subPath string) *RouteBuilder func (w *WebService) PUT(subPath string) *RouteBuilder func (w *WebService) PATCH(subPath string) *RouteBuilder func (w *WebService) DELETE(subPath string) *RouteBuilder func (w *WebService) OPTIONS(subPath string) *RouteBuilder ``` -------------------------------- ### ReadEntity usage example Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/request.md Example of using ReadEntity to unmarshal a request body into a User struct, handling ServiceError and other errors appropriately. ```go func createUser(req *restful.Request, resp *restful.Response) { usr := User{} if err := req.ReadEntity(&usr); err != nil { if serr, ok := err.(restful.ServiceError); ok { resp.WriteServiceError(serr.Code, serr) // e.g. 400 Unable to unmarshal... } else { resp.WriteError(http.StatusInternalServerError, err) } return } resp.WriteHeaderAndEntity(http.StatusCreated, usr) } ``` -------------------------------- ### NewError usage example Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/service-error.md Example of creating a ServiceError with NewError and printing its error message. The output shows the formatted error string. ```go err := restful.NewError(http.StatusNotFound, "404: Page Not Found") fmt.Println(err.Error()) // "[ServiceError:404] 404: Page Not Found" ``` -------------------------------- ### BodyParameter usage example Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/request.md Example of calling BodyParameter to retrieve a form field value, handling the error by writing a bad request response. ```go name, err := req.BodyParameter("name") if err != nil { resp.WriteError(http.StatusBadRequest, err) return } ``` -------------------------------- ### NewErrorWithHeader usage example Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/service-error.md Example of creating a ServiceError with custom headers using NewErrorWithHeader. Useful for setting response headers like Allow for 405 errors. ```go err := restful.NewErrorWithHeader( http.StatusMethodNotAllowed, "405: Method Not Allowed", http.Header{"Allow": []string{"GET, PUT"}}) ``` -------------------------------- ### CurrentCompressorProvider / SetCompressorProvider Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/entities-and-encoding.md Functions to get and set the active CompressorProvider. ```APIDOC ## CurrentCompressorProvider / SetCompressorProvider ### Description CurrentCompressorProvider returns the active provider. SetCompressorProvider replaces the provider. ### Functions - **CurrentCompressorProvider()** (CompressorProvider) - Returns the active provider. Default: NewSyncPoolCompessors(). - **SetCompressorProvider(p CompressorProvider)** - Replaces the provider. Panics with "cannot set compressor provider to nil" if p == nil. ``` -------------------------------- ### WebService configuration methods Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/webservice.md These methods configure the WebService: Path sets the root URL template, RootPath returns it, ApiVersion/Version set and return the API version, and Doc/Documentation set and return the documentation text. ```go // web_service.go:80 func (w *WebService) Path(root string) *WebService // web_service.go:242 func (w *WebService) RootPath() string // web_service.go:70 func (w *WebService) ApiVersion(apiVersion string) *WebService // web_service.go:76 func (w *WebService) Version() string // web_service.go:258 func (w *WebService) Doc(plainText string) *WebService // web_service.go:264 func (w *WebService) Documentation() string ``` -------------------------------- ### EnableTracing Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/logging.md Turns tracing on/off. When on, trace messages are emitted through the logger installed by TraceLogger. ```APIDOC ## EnableTracing ### Description Turns tracing on/off. When on, trace messages are emitted through the logger installed by `TraceLogger`. ### Function Signature ```go func EnableTracing(enabled bool) ``` ### Parameters - **enabled** (bool) - Required - Set to true to enable tracing, false to disable. ### Example ```go // later, to switch it off without changing the logger: restful.EnableTracing(false) ``` ``` -------------------------------- ### DefaultRequestContentType usage example Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/request.md Configures the fallback content type to JSON for requests without a recognized Content-Type. ```go restful.DefaultRequestContentType(restful.MIME_JSON) ``` -------------------------------- ### DefaultResponseContentType example Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/response.md Sets the default response content type to JSON. This value is used when no Accept header match is found. ```go restful.DefaultResponseContentType(restful.MIME_JSON) ``` -------------------------------- ### Basic logging and short-circuiting auth filters Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/filters.md Shows two filter functions: a logging filter that logs the request method and URL then continues the chain, and an authentication filter that short-circuits by writing a 401 error and returning without calling ProcessFilter when the Authorization header is missing. Also demonstrates registering filters at container, WebService, and Route levels. ```go // Basic filter: log, then continue func logging(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { log.Printf("[filter] %s %s", req.Request.Method, req.Request.URL) chain.ProcessFilter(req, resp) } // Short-circuiting filter: respond without calling the route func auth(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { if req.HeaderParameter("Authorization") == "" { resp.WriteErrorString(http.StatusUnauthorized, "missing token") return // chain not continued → route never runs } chain.ProcessFilter(req, resp) } restful.Filter(logging) // container level ws.Filter(logging).Filter(measure) // webservice level ws.Route(ws.GET("/x").Filter(auth).To(handler)) // route level ``` -------------------------------- ### ServeHTTP method signature Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/container.md Implements http.Handler, allowing a Container to be used as an http.Server handler. Delegates to ServeMux.ServeHTTP with optional compression wrapping. ```go // container.go:313 func (c *Container) ServeHTTP(httpWriter http.ResponseWriter, httpRequest *http.Request) ``` -------------------------------- ### Register NoBrowserCacheFilter with restful.Filter Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/filters.md Registers the NoBrowserCacheFilter as a global filter using restful.Filter. Place this in your application setup to apply anti-caching headers to all responses. ```go restful.Filter(restful.NoBrowserCacheFilter) ``` -------------------------------- ### Param and PathParameters method signatures Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/webservice.md Shows the method signatures for Param and PathParameters as defined in web_service.go. Use these to append a parameter to the root path or retrieve the shared path parameter docs. ```go // web_service.go:90 func (w *WebService) Param(parameter *Parameter) *WebService // web_service.go:247 func (w *WebService) PathParameters() []*Parameter ``` -------------------------------- ### NewContainer constructor (container.go:36) Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/container.md Creates a new Container with a fresh http.NewServeMux(), empty filter list, doNotRecover set to true, default recover handler logStackOnRecover, default service-error handler writeServiceError, router CurlyRouter{}, and content encoding disabled. Returns a *Container ready for Add(service) calls. ```go // container.go:36 func NewContainer() *Container ``` -------------------------------- ### EntityWriter usage example Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/response.md Checks if an EntityWriter is available; if not, writes a 406 Not Acceptable status. Otherwise, writes the payload with a 200 OK status using the returned writer. ```go if w, ok := resp.EntityWriter(); !ok { resp.WriteHeader(http.StatusNotAcceptable) } else { _ = w.Write(resp, http.StatusOK, payload) } ``` -------------------------------- ### RouteBuilder.Doc Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/routebuilder.md Sets the route's short documentation string. ```APIDOC ## RouteBuilder.Doc ### Description Sets a short description of the route for documentation purposes. ### Method Doc ### Signature `func (b *RouteBuilder) Doc(documentation string) *RouteBuilder` ### Parameters - **documentation** (`string`) - Required - Short description of the route. ``` -------------------------------- ### WriteEntity and WriteHeaderAndEntity example Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/response.md Writes a user entity with default status 200, or with a custom status 201. The response body is serialized based on the request's Accept header. ```go resp.WriteEntity(user) // 200 + JSON/XML resp.WriteHeaderAndEntity(http.StatusCreated, user) // 201 ``` -------------------------------- ### String method (route.go:180) Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/routebuilder.md Debugging helper that returns the route's method and path as a string. ```go // route.go:180 func (r *Route) String() string ``` -------------------------------- ### Header/serialization control method signatures (response.go) Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/response.md Declarations for PrettyPrint, AddHeader, and SetRequestAccepts. PrettyPrint overrides pretty JSON/XML output per response, AddHeader is a chainable header shortcut, and SetRequestAccepts sets the request Accept value for testing. ```go // response.go:66 func (r *Response) PrettyPrint(bePretty bool) // response.go:71 func (r Response) AddHeader(header string, value string) Response // response.go:77 func (r *Response) SetRequestAccepts(mime string) ``` -------------------------------- ### TypeNameHandler usage example Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/webservice.md Registers a custom type name handler that wraps pointer type names in guillemets. Use this to customize the documentation string for body parameter data types. ```go ws.TypeNameHandler(func(sample interface{}) string { if t := reflect.TypeOf(sample); t.Kind() == reflect.Ptr { return "«" + t.Elem().Name() + "»" } return "«" + t.Name() + "»" }) ``` -------------------------------- ### Catching a ServiceError from ReadEntity Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/service-error.md Example of catching a ServiceError returned from ReadEntity using a type assertion. If the error is a ServiceError, it writes a service error response; otherwise, it writes a 500 error. ```go func handler(req *restful.Request, resp *restful.Response) { var u User if err := req.ReadEntity(&u); err != nil { if serr, ok := err.(restful.ServiceError); ok { // 400 Unable to unmarshal content of type:... resp.WriteServiceError(serr.Code, serr) } else { resp.WriteError(http.StatusInternalServerError, err) } return } resp.WriteEntity(u) } ``` -------------------------------- ### Error writer usage example Source: https://github.com/emicklei/go-restful/blob/v3/_autodocs/api-reference/response.md Shows how to use WriteErrorString, WriteError, and WriteServiceError in a handler. WriteErrorString is used for a not-found case, WriteError for an internal server error, and WriteServiceError for a bad request with a restful.NewError. ```go if user == nil { resp.WriteErrorString(http.StatusNotFound, "user not found") return } resp.WriteError(http.StatusInternalServerError, err) resp.WriteServiceError(http.StatusBadRequest, restful.NewError(http.StatusBadRequest, "bad input")) ```