C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
HandleFunc: For each func used with HandleFunc, we receive 2 arguments. We can use the ResponseWriter to write a response.
And: We can test the http.Request for more information like the URL and its Path.
Golang program that uses http.ListenAndServe
package main
import (
"fmt"
"html"
"log"
"net/http"
)
func test0(w http.ResponseWriter, r *http.Request) {
// Handles top-level page.
fmt.Fprintf(w, "You are on the home page")
}
func test1(w http.ResponseWriter, r *http.Request) {
// Handles about page.
// ... Get the path from the URL of the request.
path := html.EscapeString(r.URL.Path)
fmt.Fprintf(w, "Now you are on: %q", path)
}
func test2(w http.ResponseWriter, r *http.Request) {
// Handles "images" page.
fmt.Fprintf(w, "Image page")
}
func main() {
// Add handle funcs for 3 pages.
http.HandleFunc("/", test0)
http.HandleFunc("/about", test1)
http.HandleFunc("/images", test2)
// Run the web server.
log.Fatal(http.ListenAndServe(":8080", nil))
}
Tip: After running Go on the program, open your web browser and type in the localhost domain.
Then: Go to "/about" and "images" on the localhost domain. The pages should show the messages from the test methods.
Type into browser:
http://localhost:8080
http://localhost:8080/about
http://localhost:8080/images
Here: We read in a local image from the disk. We write its bytes to the response when the "image" path is accessed.
And: Checking the headers, we can see that the response has the correct content type of "image/jpeg."
Golang program that uses Header, writes image
package main
import (
"bufio"
"io/ioutil"
"log"
"net/http"
"os"
)
func Image(w http.ResponseWriter, r *http.Request) {
// Open a JPG file.
f, _ := os.Open("/home/sam/coin.jpg")
// Read the entire JPG file into memory.
reader := bufio.NewReader(f)
content, _ := ioutil.ReadAll(reader)
// Set the Content Type header.
w.Header().Set("Content-Type", "image/jpeg")
// Write the image to the response.
w.Write(content)
}
func main() {
// Use this URL.
http.HandleFunc("/image", Image)
// Run.
log.Fatal(http.ListenAndServe(":8080", nil))
}