I'm writing a simple rest api server and I cannot get route dynamic url using net/http
http://localhost:8080/book/name
where name can be any string.
this was my attempt:
func viewIndex(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, 'html')
}
http.HandleFunc("/book/{name}", view)
this does not work, there is some cryptic note in the documentation of HandleFunc:
The documentation for ServeMux explains how patterns are matched.
This is a working solution.
The only interesting part it that patterns ending with / will be treated as prefix matcher for all urls.
So pattern /book/ will match:
/book/
/book/a
/book/bb
/book/a/b
sample simplified code:
package main
import (
"fmt"
"strings"
"net/http"
)
func book(name string) {
fmt.Printf("requesting book '%s'\n",name);
}
func view(w http.ResponseWriter, r *http.Request) {
url := r.URL.String()
if strings.HasPrefix(url, "/book/"){
name := url[6:]
book(name)
fmt.Fprint(w, name)
}
}
func main() {
http.HandleFunc("/book/", view)
http.ListenAndServe("localhost:8080", nil)
}
Related
Probably there is already a solution here to my problem, but I couldn't find it anywhere. I tried a bunch of stuff, but nothing worked so far.
I have something like this:
package main
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
)
func HealthCheck(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, "Healthy")
// Also print the value of 'foo'
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/health-check", HealthCheck).Methods("GET").Queries("foo", "{foo}").Name("HealthCheck")
r.HandleFunc("/health-check", HealthCheck).Methods("GET")
http.ListenAndServe(":8080", r)
}
What I'm trying to achieve:
curl http://localhost:8080/health-check
Should respond with: Healthy <foo> ( -> the default value of foo)
And also the following:
curl http://localhost:8080/health-check?foo=bar
Should respond with: Healthy bar
One solution if to simply handle the query params in your handler:
package main
import (
"net/http"
"github.com/gorilla/mux"
)
func HealthCheckHandler(w http.ResponseWriter, req *http.Request) {
values := req.URL.Query()
foo := values.Get("foo")
if foo != "" {
w.Write([]byte("Healthy " + foo))
} else {
w.Write([]byte("Healthy <foo>"))
}
w.WriteHeader(http.StatusOK)
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/health-check", HealthCheckHandler)
http.ListenAndServe(":8080", r)
}
according to the gorilla/mux documentation, the Queries method is meant to match your handler to specific functions, akin to a regular expression.
I'm trying to pick out a value in the request.body but I keep getting an empty string.
The Form map is also coming up as empty.
What am I doing wrong?
package user
import (
"fmt"
"net/http"
"../../types"
)
func PostTest(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
x := r.FormValue("name")
fmt.Println(x)
}
The body of the post request:
{
"name":"Tom",
"age":25
}
The reason is because the request body is not valid form data, but a blob of JSON data. You will need to parse it before being able to extract the name, e.g.:
type data struct {
Name string
Age int
}
func PostTest(w http.ResponseWriter, r *http.Request) {
var d data
json.NewDecoder(r.Body).Decode(&d) // Error handling omitted.
fmt.Println(d.Name)
}
Here's a Playground demonstrating this. I have omitted error handling for brevity.
I am new to golang and using julienschmidt/httprouter for routing.
based on below snippet, able to send one parameter.
but I am little confused to send multiple parameters, cloud anyone helps me.
package main
import (
"fmt"
"github.com/julienschmidt/httprouter"
"net/http"
"log"
)
func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
fmt.Fprint(w, "Welcome!\n")
}
func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
}
func main() {
router := httprouter.New()
router.GET("/", Index)
router.GET("/hello/:name", Hello)
log.Fatal(http.ListenAndServe(":8080", router))
}
Just add in another parameter:
router.GET("/hello/:first_name/:last_name", Hello)
func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
fmt.Fprintf(w, "hello, %s %s!\n", ps.ByName("first_name"), ps.ByName("last_name"))
}
I am having issues getting the Gorilla Mux library for Go to work. From the documentation I have read and all the debugging I've done, I cannot seem to figure out what the problem is. Here's what I've got for routing:
Folder structure:
project_root
|-- main.go
|-- routes
|-- routes.go
|-- user.go
main.go:
package main
import (
"fmt"
"net/http"
"./routes"
)
func main() {
r := routes.CreateRoutes(http.Dir("./content"))
http.Handle("/", r)
err := http.ListenAndServe(fmt.Sprintf("%s:%d", "localhost", 8000), nil)
if err != nil {
fmt.Println("Error: ", err)
}
}
routes/routes.go
package routes
import (
"net/http"
"github.com/gorilla/mux"
)
func CreateRoutes(staticDir http.FileSystem) *mux.Router {
r := mux.NewRouter()
// Serve static pages (i.e. web app)
r.PathPrefix("/").Handler(http.FileServer(staticDir))
// Serve User Pages
createUserRoutes(r)
return r
}
routes/user.go
package routes
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
)
func createUserRoutes(r *mux.Router) {
user := r.PathPrefix("/user/").Subrouter()
// Create a new user
user.Path("/new").Methods("PUT").HandlerFunc(newUserHandler)
// Remove a user
user.Path("/remove/{username:[a-z][a-z0-9]+}").Methods("DELETE").HandlerFunc(removeUserHandler)
// Update a user
user.Path("update/{username:[a-z][a-z0-9]+").Methods("POST").HandlerFunc(updateUserHandler)
// Get a user (Get user information)
user.Path("/{username:[a-z][a-z0-9]+").Methods("GET").HandlerFunc(getUserHandler)
}
func newUserHandler(resp http.ResponseWriter, req *http.Request) {
// Do something that might cause an error
if err != nil {
fmt.Println(err)
resp.WriteHeader(409)
resp.Write([]byte(err.Error()))
} else {
fmt.Println("Created new user")
resp.WriteHeader(201)
resp.Write([]byte("Created new user"))
}
}
func removeUserHandler(resp http.ResponseWriter, req *http.Request) {
}
func updateUserHandler(resp http.ResponseWriter, req *http.Request) {
}
func getUserHandler(resp http.ResponseWriter, req *http.Request) {
}
Whenever I make a request to root path of the server (i.e. the path that serves the static content), the server responds as intended, with the main page. However, any other calls result in a 404 response (I test requests using cURL). For example, a malformed request to http://localhost:8000/user/new should return a 409, but instead returns a 404. Same if I expect a 201 response.
Everything looks right and I've triple checked it, but I cannot figure out what the issue here is.
Turns out the solution was simple (like it usually is). This line in routes.go
r.PathPrefix("/").Handler(http.FileServer(staticDir))
was causing the unintended routing. When PathPrefix is used, it seems to route all URLs to the first matching prefix (in this case this prefix). This explains why static files were being served, but nothing else works.
The fix is to use the Path function instead. There's a subtle difference as explained in the docs; PathPrefix "matches if the given template is a prefix of the full URL path", whereas Path does not. Hence the line above now looks like this to solve the issue I was having:
r.Path("/").Handler(http.FileServer(staticDir))
Adding an encoded string to an http resonse seems to replace some characters with !F(MISSING). How that that be prevented?
Output:
{"encodedText":"M6c8RqL61nMFy%!F(MISSING)hQmciSYrh9ZXgVFVjO"}
Code:
package main
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
)
type EncodeResult struct {
EncodedText string `json:"encodedText"`
}
func main() {
http.HandleFunc("/encodedString", encodedString)
_ = http.ListenAndServe(":8080", nil)
}
func encodedString(w http.ResponseWriter, r *http.Request) {
inputString := "M6c8RqL61nMFy/hQmciSYrh9ZXgVFVjO"
er := EncodeResult{url.QueryEscape(inputString)}
response, _ := json.Marshal(er)
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, string(response))
}
It appears to be escaping it normally, can you paste some code?
http://play.golang.org/p/rUEGn-KlTX
package main
import (
"fmt"
"net/url"
)
func main() {
escape := url.QueryEscape("M6c8RqL61nMFy/hQmciSYrh9ZXgVFVjO")
fmt.Println(escape)
}
You are using the escaped value "M6c8RqL61nMFy%2FhQmciSYrh9ZXgVFVjO " as a format string on this line:
fmt.Fprintf(w, string(response))
Fprintf attempts to format an argument for the verb "%2F". There is no argument, so Fprintf prints "%!F(MISSING)" for the verb.
The fix is to not use the output as a format string. Because you don't need any formatting when writing to the response, change the last line to:
w.Write(response)