I currently have my routes set for my REST API as:
using mux
localhost:8080/user/{id}
localhost:8080/space/{id}
server.Router.HandleFunc("/users", middlewares.SetMiddlewareJSON(server.GetUsers)).Methods("GET")
server.Router.HandleFunc("/posts", middlewares.SetMiddlewareJSON(server.GetPosts)).Methods("GET")
the set middleware function
func SetMiddlewareJSON(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
next(w, r)
}
}
How would I combine them to become
localhost:8080/user/1/post/{id}
the repository for the project is here:
https://github.com/Robbie-Thomas/fullstack
You will need a HandlerFunc with that path:
server.Router.HandleFunc("/users/{userId}/post/{id}", middlewares.SetMiddlewareJSON(server.GetUsers)).Methods("GET")
In the handler func, you'll access those variables:
vars:=mux.Vars(request)
userId:=vars["userId"]
postId:=vars["id"]
Related
I am trying to create a route for GET request with the username parameter. After sending the request from postman as localhost:9090/user/?username=abc I am unable to get the response. It is showing 404 error.
func main() {
router := gin.Default()
router.POST("/user", controllers.CreateUser)
router.GET("/user/:username", GetUser)
router.HEAD("/user/:username", controllers.GetUserMeta)
router.Run("localhost:9090")
}
func GetUser(context *gin.Context) {
// get specific record from database
uname := context.Param("username")
fmt.Println("received:", uname)
//context.IndentedJSON(http.StatusOK, user)
}
I am wondering why the GetUser method is not executed.
With a single API resource /, we have written only one handler that process GET & POST request on API resource /
POST we use to create a resource in database, byt sending data in request body
PUT we use to update an existing resource in database
My understanding is, RESTful best practice says, a handler need to serve an API resource(say /) for all requests GET, POST & PUT
We want the same handler to process PUT request, but the API resource will be something like /1234, where 1234 is existing id
Technically, API resource /1234 will also map to same handler that processes /, but,
From RESTful best practices, Does /1234 need to be handled without passing id as part of API resource URI? something like below...
func ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet { // for API resource '/'
p.getProducts(w, r)
return
}
if r.Method == http.MethodPost { // for API resource '/'
p.addProduct(w, r)
return
}
if r.Method == http.MethodPut { // for API resource '/'
p.updateProduct(w, r)
return
}
}
func updateProduct(w http.ResponseWriter, r *http.Request) {
var idString string
decoder := json.NewDecoder(r.Body)
decoder.Decode(idString)
id, err := findID(idString)
// do whatever with id
}
func findID(str string) (int, error) {
dfa := regexp.MustCompile(`/([0-9]+)`)
matches := dfa.FindAllStringSubmatch(str, -1) // returns [][]string
idString := matches[0][1]
id, err := strconv.Atoi(idString)
return id, nil
}
As I understood right you right.
You have two call which can be handle without Id for end point /.
One is POST when the back-end with generate you Id as a result.
Second is GET for all resources but this is up to you. Maybe because of secure reason you would not like to list all available resources.
One extra information is that PUT & 'POST' can use the same handler but logic in handler has to check if 'id' is provided and do extra more logic to create resource.
I am using auth0 and golang for a rest service that is similar implemented as shown here.
I wonder how I can find out the name of the user that is currently triggering a certain API call - for instance if someone requests http://localhost:3000/products - the go handler in this case looks like this:
var ProductsHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
payload, _ := json.Marshal(products)
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(payload))
})
Does the request r contain more information about the current user?
Or do I need to find out the current user in the middleware authentication:
func authMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
secret := []byte("{YOUR-AUTH0-API-SECRET}")
secretProvider := auth0.NewKeyProvider(secret)
audience := "{YOUR-AUTH0-API-AUDIENCE}"
configuration := auth0.NewConfiguration(secretProvider, audience, "https://{YOUR-AUTH0-DOMAIN}.auth0.com/", jose.HS256)
validator := auth0.NewValidator(configuration)
token, err := validator.ValidateRequest(r)
if err != nil {
fmt.Println(err)
fmt.Println("Token is not valid:", token)
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("Unauthorized"))
} else {
next.ServeHTTP(w, r)
}
})
}
Does the token contain more information about the user?
I am a bit lost here. auth0 works perfectly to ensure that only registered persons can use the REST-API, but I want to deliver user specific information. So it depends on the current user what a REST call is handing back. Initially, I was thinking that auth0 would take care of this. Is there a simple way to achieve this?
Yes, you need to use token to get information about request issue.
To sort all you want you need to take a look to next:
Check out how token extracted in this method: token extraction
And the Claims here: Claims structure
And how combine it here: retrieve Claims
The claims have a field
Issuer string `json:"iss,omitempty"`
you are interested in.
I am interested in dynamically taking arguments from the user as input through a browser or a CLI to pass in those parameters to the REST API call and hence construct the URL dynamically using Go which is going to ultimately fetch me some JSON data.
I want to know some techniques in Go which could help me do that. One ideal way I thought was to use a map and populate it with arguments keys and corresponding values and iterate over it and append it to the URL string. But when it comes to dynamically taking the arguments and populating the map, I am not very sure how to do that in Go. Can someone help me out with some code snippet in Go?
Request example:
http://<IP>:port?api=fetchJsonData&arg1=val1&arg2=val2&arg3=val3.....&argn=valn
There's already url.URL that handles that kind of things for you.
For http handlers (incoming requests) it's a part of http.Request (access it with req.URL.Query()).
A very good example from the official docs:
u, err := url.Parse("http://bing.com/search?q=dotnet")
if err != nil {
log.Fatal(err)
}
u.Scheme = "https"
u.Host = "google.com"
q := u.Query()
q.Set("q", "golang")
u.RawQuery = q.Encode()
fmt.Println(u)
https://github.com/golang/go/issues/17340#issuecomment-251537687
https://play.golang.org/p/XUctl_odTSb
package main
import (
"fmt"
"net/url"
)
func someURL() string {
url := url.URL{
Scheme: "https",
Host: "example.com",
}
return url.String()
}
func main() {
fmt.Println(someURL())
}
returns:
https://example.com
url.Values{} provides an interface for building query params. You can construct inline and/or use .Add for dynamic properties:
queryParams := url.Values{
"checkin": {request.CheckIn},
"checkout": {request.CheckOut},
}
if request.ReservationId {
queryParams.Add("reservationId", request.ReservationId)
}
url := "https://api.example?" + queryParams.Encode() // checkin=...&checkout=...
In Golang, how do I serve static content out of the root directory while still having a root directory handler for serving the homepage.
Use the following simple web server as an example:
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", HomeHandler) // homepage
http.ListenAndServe(":8080", nil)
}
func HomeHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "HomeHandler")
}
If I do
http.Handle("/", http.FileServer(http.Dir("./")))
I receive a panic saying that I have two registrations for "/". Every Golang example I've found on the internet suggests serving their static content out of different directories, but that doesn't help much for things like sitemap.xml, favicon.ico, robots.txt and other files which are by-practice or mandated to always be served out of the root.
The behavior I seek is the behavior which is found in most web servers such as Apache, Nginx, or IIS, where it first traverses your rules, and if no rule is found it looks for an actual file, and if no file is found it 404s. My guess is that instead of writing a http.HandlerFunc, I need to write a http.Handler which checks if I am referencing a file with an extension, and if so checks for file existence and serves the file, otherwise it 404s or serves the homepage is the request was for "/". Unfortunately I'm not certain how to even begin such a task.
Part of me says I'm massively over-complicating the situation which makes me think that I am missing something? Any guidance would be appreciated.
An alternative (not using ServeMux) solution is to serve explicitly each file located in the root directory. The idea behind is to keep the number of root-based files very small.
sitemap.xml, favicon.ico, robots.txt are indeed mandated to be served out of the root :
package main
import (
"fmt"
"net/http"
)
func HomeHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "HomeHandler")
}
func serveSingle(pattern string, filename string) {
http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, filename)
})
}
func main() {
http.HandleFunc("/", HomeHandler) // homepage
// Mandatory root-based resources
serveSingle("/sitemap.xml", "./sitemap.xml")
serveSingle("/favicon.ico", "./favicon.ico")
serveSingle("/robots.txt", "./robots.txt")
// Normal resources
http.Handle("/static", http.FileServer(http.Dir("./static/")))
http.ListenAndServe(":8080", nil)
}
Please move all other resources (CSS, JS, etc.) to a proper subdirectory, e.g. /static/ .
One thing I thought of that might help you is that you can create your own ServeMux. I added to your example so that chttp is a ServeMux that you can have serve static files. The HomeHandler then checks to see if it should serve a file or not. I just check for a "." but you could do a lot of things. Just an idea, might not be what you are looking for.
package main
import (
"fmt"
"net/http"
"strings"
)
var chttp = http.NewServeMux()
func main() {
chttp.Handle("/", http.FileServer(http.Dir("./")))
http.HandleFunc("/", HomeHandler) // homepage
http.ListenAndServe(":8080", nil)
}
func HomeHandler(w http.ResponseWriter, r *http.Request) {
if (strings.Contains(r.URL.Path, ".")) {
chttp.ServeHTTP(w, r)
} else {
fmt.Fprintf(w, "HomeHandler")
}
}
Using Gorilla mux package :
r := mux.NewRouter()
//put your regular handlers here
//then comes root handler
r.HandleFunc("/", homePageHandler)
//if a path not found until now, e.g. "/image/tiny.png"
//this will look at "./public/image/tiny.png" at filesystem
r.PathPrefix("/").Handler(http.FileServer(http.Dir("./public/")))
http.Handle("/", r)
http.ListenAndServe(":8080", nil)