Go URL path parameter
We can send data to the server in the URL.
package main
import(
"fmt"
"log"
"net/http"
)
func main(){
http.HandleFunc("/", temp)
fmt.Printf("Starting server for port 9000\n")
err:=http.ListenAndServe(":9000", nil)
if err!=nil{
log.Fatal(err)
}
}
func temp(w http.ResponseWriter, r*http.Request){
fmt.Fprintf(w, "Hello, %s\n",r.URL.Path[1:])
}
Output
In the above program, we can get the URL path value with r.URL.Path[1:] that we will send inside the URL(http://localhost:9000/Ninjas) path.
After starting the server, if we run the command $curl localhost:9000/Ninjas on our command prompt, we get the output Hello, Ninjas.
Go query parameter
A query string is a part of a URL(uniform resource locator) that assigns values to specified parameters.
A generic URL has the following form:
scheme ":" ["//" authority] path ["?" query] ["#" fragment]
When an HTTP(Hypertext Transfer Protocol) request is made to a server, it is sometimes necessary to extract certain predefined query parameters from the request URL to read the values.
Here is a program on how to get the value of query parameter on a Go server.
package main
import(
"fmt"
"log"
"net/http"
)
func main(){
http.HandleFunc("/", temp)
fmt.Printf("Starting server for port 9000\n")
err:=http.ListenAndServe(":9000", nil)
if err!=nil{
log.Fatal(err)
}
}
func temp(w http.ResponseWriter, r*http.Request){
value:= r.URL.Query().Get("value")
fmt.Println("Value of query parameter=>",value)
}
Output
In the above program, We accept a value parameter. We get the parameter with r.URL.Query().Get("value").
After starting the server, if we run the command $curl localhost:9000/?value=Ninjas on our command prompt, we get the output Value of query parameter=> Ninjas.
Go file server
We use the http.FileServer() function to send files to the client.
Let us create a directory that will hold the main.go file and then create another directory that will hold some other simple HTML files. The main.go file holds our code.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home page</title>
</head>
<body>
<h1>This is the home page.</h1>
</body>
</html>
form.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<div>
<form method="POST" action="/">
<label>E-mail</label><input name="email" type="text" value="" />
<br>
<label>Password</label><input name="Password" type="password" value="" />
<input type="submit" value="submit" />
</form>
</div>
</body>
</html>
main.go
package main
import (
"log"
"net/http"
)
func main() {
fs := http.FileServer(http.Dir("./testfiles"))
http.Handle("/", fs)
log.Println("Starting server for port 9000\n")
err := http.ListenAndServe(":9000", nil)
if err != nil {
log.Fatal(err)
}
}
In the above code, we use the http.FileServer() function to create a handler that responds to all HTTP requests with the contents of a given file system. We use the http.Handle() function to register the file server as the handler for all requests and launch the server listening on port 9000.
After starting the server, if we run the command $curl localhost:9000/ and $curl localhost:9000/form.html on our command prompt, we get
Go process GET/POST request
Here we create two different files named form.html and main.go.
form.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<div>
<form method="POST" action="/">
<label>E-mail</label><input name="email" type="text" value="" />
<br>
<br>
<label>Password</label><input name="password" type="password" value="" />
<br>
<input type="submit" value="submit" />
</form>
</div>
</body>
</html>
main.go
package main
import (
"fmt"
"log"
"net/http"
)
func temp(w http.ResponseWriter, r *http.Request) {
if r.URL.Path!="/"{
http.Error(w, "404 not found.", http.StatusNotFound)
return
}
switch r.Method{
case "GET":
http.ServeFile(w, r, "form.html")
case "POST":
if err := r.ParseForm(); err != nil {
fmt.Fprintf(w, "ParseForm() err: %v",err)
return
}
fmt.Fprintf(w, "Post from website! r.PostFrom = %v\n", r.PostForm)
email:=r.FormValue("email")
password:= r.FormValue("password")
fmt.Fprintf(w, "E-mail = %s\n",email)
fmt.Fprintf(w, "Password = %s\n",password)
default:
fmt.Fprintf(w, "Sorry, only GET and POST methods are supported.")
}
}
func main() {
http.HandleFunc("/", temp)
fmt.Printf("Starting server at port 9000 for HTTP POST\n")
if err := http.ListenAndServe(":9000", nil);
err!=nil{
log.Fatal(err)
}
}
In the above code, For a GET request, we send the form.html to the client, and For a POST request, we call the ParseForm function; it parses the raw query from the URL and updates r.Form.
After starting the server, when we run URL http://localhost:9000/ in our browser and see the below content.
After submitting the form
FAQs
-
Can Golang be used for web development?
Ans: Golang is a relatively new language in the programming world, but it has proved suitable for web development by supporting Google, YouTube, Netflix, and Uber. It is designed to enable developers to rapidly develop scalable and secure web applications.
-
What is default Servemux?
Ans: The default servemux is stored in a global variable. Any package can access it and register a route — including any third-party packages that your application imports.
-
What is an HTTP request multiplexer?
Ans: In the Go language, ServeMux is an HTTP request multiplexer. It is responsible for matching the URL in the request to an appropriate handler and executing it.
Key takeaways
In this article, we have extensively discussed the HTTP server in the Go programming language. We also discussed how we could create HTTP servers in Golang and do several operations on it.
Also, Read - Demultiplexer
We hope that this blog has helped you enhance your knowledge regarding the Go HTTP server and if you would like to learn more, check out our article on Go Directories. You can read about C language articles by clicking C Archives. Do upvote our blog to help ninjas grow. Happy Coding!